Physics.Raycast
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 33 of 63.
A raycast shoots an invisible line from a point in a direction and reports whether it hit a collider. Physics.Raycast(origin, direction, maxDistance) returns true when a collider lies on the line within maxDistance units, and false otherwise. This car brakes when anything is less than 2 units ahead of its nose:
public float brakeDistance = 2f;
void Update()
{
if (Physics.Raycast(transform.position, transform.forward, brakeDistance))
{
Debug.Log("Brake!");
}
}transform.forward turns with the car, so the ray always looks out of its nose; Vector3.forward would always point along the world's z axis. The ray starts at the car's centre, inside its own collider, and a ray never reports a collider it starts inside, so the car does not see itself. Leave out maxDistance and the ray runs on forever: the car would brake for a wall across the map.
Rays see colliders, not what is drawn: an object with a Renderer and no collider is invisible to them, and a trigger collider counts as a hit. While you test, Debug.DrawRay(transform.position, transform.forward * brakeDistance, Color.red) draws the ray in Unity's Scene view.
Challenge
MediumMake the shop door automatic. The DoorSensor script sits on the Sensor above the doorway, 3.5 units above the ground. The Inspector gives it the door and a reach of 3.
- Every frame, cast a ray from the Sensor straight down,
reachunits long. - While the ray hits something, the door is open: hide it with
SetActive(false). While it hits nothing, show the door again.
The ground is out of the ray's reach, so the door stays shut until someone stands under the Sensor. Press Play and walk the Visitor under it with the arrows, then Check.
Try it yourself
using UnityEngine;
public class DoorSensor : MonoBehaviour
{
public GameObject door;
public float reach = 3f;
void Update()
{
// Open the door while the ray down from the Sensor hits something.
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable Wall