Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 36 ยท Physics and Collisions

Raycasting and Layers

Use Physics.Raycast in Unity to detect what is ahead, below or under the mouse: RaycastHit, LayerMask filtering, SphereCast, OverlapSphere, debug drawing, with runnable ray math.

A raycast shoots an invisible line from a point in a direction and tells you what it hits first. It is the physics system's way of asking questions: Is the player standing on the ground? Can the enemy see me, or is a wall in between? What object is under the mouse cursor? Where does the bullet land? Raycasts are cheap, precise and used in nearly every game.

This lesson covers Physics.Raycast, the RaycastHit result, layer masks that decide what a ray can hit, and the related shape queries. The Unity code is read-only; the stand-ins compute ray-sphere and ray-plane intersections in plain C# so you can see what the engine does.

The basic raycast

C#
using UnityEngine;

public class GroundCheck : MonoBehaviour
{
    [SerializeField] float checkDistance = 1.1f;

    void Update()
    {
        if (Physics.Raycast(transform.position, Vector3.down, out RaycastHit hit, checkDistance))
        {
            Debug.Log($"Standing on {hit.collider.name} at distance {hit.distance:F2}");
        }
        else
        {
            Debug.Log("In the air");
        }
    }
}

Physics.Raycast(origin, direction, out hit, maxDistance) returns true if the ray hit a collider. The ray starts at origin, goes along direction (a normalized vector; the length of the vector is ignored) and stops at maxDistance. The out RaycastHit hit parameter is filled with the details.

RaycastHit data

Field Meaning
hit.collider The collider that was hit
hit.transform, hit.rigidbody Its transform and Rigidbody (if any)
hit.point World position of the hit
hit.normal The surface direction at the hit (perpendicular to the surface)
hit.distance Distance from the origin to the hit

Layer masks: choose what the ray can hit

By default a ray hits everything, including your own collider if it starts inside it. A LayerMask is a set of layers (a 32-bit field, one bit per layer) that limits the query:

C#
using UnityEngine;

public class Shooter : MonoBehaviour
{
    [SerializeField] LayerMask hitMask;        // pick layers in the Inspector (a multi-select drop-down)
    [SerializeField] float range = 50f;

    void Update()
    {
        if (!Input.GetButtonDown("Fire1")) return;

        if (Physics.Raycast(transform.position, transform.forward, out RaycastHit hit, range, hitMask))
        {
            Debug.Log("Hit " + hit.collider.name);
            if (hit.collider.TryGetComponent<Health>(out var health))
                health.TakeDamage(25);
        }
    }
}

In code, you can build masks with LayerMask.GetMask("Enemy", "Ground") or bit operations (1 << 9 is layer 9). To hit everything except a layer, invert the mask: ~(1 << 8). A practical use: put the player on the Player layer and exclude that layer so the ray never hits yourself.

You set the layer of an object in the Inspector (the Layer drop-down at the top) or with gameObject.layer = 9. Which layers collide with each other physically is configured in Edit > Project Settings > Physics > Layer Collision Matrix. Layer masks in queries are separate from the matrix: they only filter that one query.

Raycast from the camera: clicking things

C#
using UnityEngine;

public class Picker : MonoBehaviour
{
    [SerializeField] Camera cam;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = cam.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit, 100f))
            {
                Debug.Log("Clicked " + hit.collider.name + " at " + hit.point);
            }
        }
    }
}

ScreenPointToRay converts a pixel position into a ray from the camera through that pixel. This is how you select units, place buildings and aim with the mouse. For 2D games use Physics2D.Raycast (it returns a RaycastHit2D and takes a Vector2), or Physics2D.GetRayIntersection.

Seeing your rays

Rays are invisible. Use Debug.DrawRay (and Debug.DrawLine) to draw them in the Scene view while the game runs:

C#
Debug.DrawRay(transform.position, transform.forward * range, Color.red);

Gizmos are another option: implement OnDrawGizmosSelected() and call Gizmos.DrawLine or Gizmos.DrawWireSphere to show ranges in the editor.

Other shape queries

Query What it asks
Physics.RaycastAll / RaycastNonAlloc Every hit along the line, not just the first
Physics.SphereCast, CapsuleCast, BoxCast A thick ray: sweep a shape along a direction (more forgiving for characters)
Physics.Linecast(a, b) Is anything between two points? Perfect for line of sight
Physics.CheckSphere(p, r) Is anything inside this sphere? (bool)
Physics.OverlapSphere(p, r) Which colliders are inside this sphere? (explosions, proximity)
Physics.OverlapBox, OverlapCapsule Same with other shapes
Physics.ComputePenetration Advanced depenetration

The NonAlloc versions fill a buffer you provide (new Collider[16]) and avoid garbage, which matters if you call them every frame.

C#
// Line of sight: can this enemy see the player?
bool CanSee(Transform target)
{
    Vector3 from = transform.position + Vector3.up;
    Vector3 to = target.position + Vector3.up;
    return !Physics.Linecast(from, to, wallMask);        // true if no wall is in between
}

// Explosion: push everything nearby away
void Explode(Vector3 center, float radius, float power)
{
    foreach (Collider c in Physics.OverlapSphere(center, radius))
        if (c.attachedRigidbody != null)
            c.attachedRigidbody.AddExplosionForce(power, center, radius);
}

What a raycast computes: ray versus sphere

Under the hood the engine solves for where a line meets a shape. For a sphere centered at C with radius r, a ray O + t*D hits it where |O + t*D - C| = r, which gives a quadratic in t. This stand-in implements that test. Try different origins and directions.

C# Ray versus sphere (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The first hit for the straight ray is at 8.5 (center at 10, minus the radius 1.5). The "behind" ray gets no hit because the sphere is in the opposite direction, and a short maxDistance can also miss it, exactly like the real maxDistance argument.

Raycast against a ground plane: mouse placement

Placing objects on the ground with the mouse often uses a mathematical plane instead of a physics hit. Unity has Plane for that; the intersection formula is simple, shown here for the plane y = 0.

C# Ray versus the ground plane (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

In Unity you would write new Plane(Vector3.up, Vector3.zero).Raycast(ray, out float enter) and then ray.GetPoint(enter).

Performance and gotchas

  • A raycast is cheap, but hundreds per frame add up: use layer masks to narrow them, and prefer NonAlloc or the newer RaycastCommand batch for large counts.
  • A ray that starts inside a collider ignores that collider's back faces (it does not hit it), unless Physics.queriesHitBackfaces is on.
  • Triggers are ignored by default; pass QueryTriggerInteraction.Collide to hit them.
  • Normalize your direction when you also use it elsewhere; the raycast itself ignores its length, but Debug.DrawRay uses it.
  • Do not raycast in Update for what OnCollisionStay already gives you.
  • In 2D, use Physics2D (not Physics), and remember Z does not matter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Physics.Raycast return?

    Raycast returns true or false, and fills the RaycastHit with details.
  2. 2. How do you make a ray ignore the Player layer?

    Layer masks restrict the query; invert the bit to exclude a layer.
  3. 3. Which method best tests whether a wall blocks the line between an enemy and the player?

    Linecast checks for obstacles between two points, which is line-of-sight.
  4. 4. Which converts a mouse position into a ray?

    ScreenPointToRay creates a ray from the camera through the screen pixel.

Summary

  • Physics.Raycast(origin, direction, out hit, maxDistance, layerMask) finds the first collider along a line.
  • RaycastHit gives the collider, point, normal and distance.
  • Layer masks filter what a query can hit; build them with the Inspector, GetMask or bit shifts.
  • ScreenPointToRay turns clicks into rays; Linecast, SphereCast and OverlapSphere cover line of sight, thick rays and area queries.
  • Draw rays with Debug.DrawRay and keep per-frame query counts under control.

Next: Forces, Physics Materials and Joints