Physics.Raycast
Part of the Physics and Gameplay section of Coddy's Unity journey. Lesson 35 of 71.
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 open while someone stands under the sensor.
- In
Update(), testPhysics.Raycast(transform.position, Vector3.down, reach): a ray straight down,reachunits long, that stops above the ground. - When it is true, call
door.SetActive(false);, and in theelse,door.SetActive(true);.
Press Play and walk the Visitor under the sensor: the door opens, and shuts behind it. 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.
}
}
All lessons in Physics and Gameplay
1Rigidbody
Gravity and MassPush with AddForceJump with an ImpulseFixedUpdate for PhysicsVelocityKinematic BodiesRecap: Launch Pad4Coroutines
InvokeInvokeRepeating, CancelInvokeYour First CoroutineLoops in CoroutinesStopping CoroutinesRecap: Countdown10Project: Arena Escape
The ArenaHunters2Collisions
OnCollisionEnterWhat Did I Hit?Break on ImpactStanding on the GroundBounce and FrictionCollider ShapesRecap: Breakable WallPractice on your own: Unity playground