2D raycast unity code example
Example 1: raycast unity
RaycastHit hit;
if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Hit");
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
Debug.Log("No Hit");
}
Example 2: unity raycast 2d
using UnityEngine;public class Example : MonoBehaviour
{
public float liftForce;
public float damping;
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
} void FixedUpdate()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);
if (hit.collider != null)
{
float distance = Mathf.Abs(hit.point.y - transform.position.y);
float heightError = floatHeight - distance;
float force = liftForce * heightError - rb2D.velocity.y * damping;
rb2D.AddForce(Vector3.up * force);
}
}
}
Example 3: unity 2d raycast mouse
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
if(hit.collider != null)
{
Debug.Log ("Target name: " + hit.collider.name);
}
Example 4: unity raycast 2d
Physics2D.Raycast(Vector2 origin, Vector2 direction, float distance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, float minDepth = -Mathf.Infinity, float maxDepth = Mathf.Infinity);