Menu
CoddyTech

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 icon

Challenge

Medium

Make the shop door open while someone stands under the sensor.

  1. In Update(), test Physics.Raycast(transform.position, Vector3.down, reach): a ray straight down, reach units long, that stops above the ground.
  2. When it is true, call door.SetActive(false);, and in the else, 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

Practice on your own: Unity playground