TExcelTAD
Home › Unity with C# › Raycasts & Physics Queries

Raycasts & Physics Queries

A raycast asks the physics engine: "if I fire an infinitely thin line from here in this direction, what does it hit first?" Shooting, line-of-sight checks, ground detection, mouse picking and interaction prompts are all raycasts or their relatives.

The basic raycast

csharp
using UnityEngine;

public class Interactor : MonoBehaviour
{
    [SerializeField] Camera cam;
    [SerializeField] float reach = 3f;
    [SerializeField] LayerMask interactMask;           // tick "Interactable" (and walls, so they block) in the Inspector

    void Update()
    {
        Ray ray = new Ray(cam.transform.position, cam.transform.forward);
        if (Physics.Raycast(ray, out RaycastHit hit, reach, interactMask, QueryTriggerInteraction.Ignore))
        {
            if (hit.collider.TryGetComponent(out IInteractable target))
                ShowPrompt(target, hit.point, hit.distance);
        }
        Debug.DrawRay(ray.origin, ray.direction * reach, Color.yellow);   // visible in the Scene view
    }

    void ShowPrompt(IInteractable target, Vector3 point, float distance) { /* ... */ }
}

public interface IInteractable { void Interact(); }

RaycastHit gives you point, normal (the surface direction, for decals and ricochets), distance, collider, rigidbody and transform. Always pass a max distance and a layer mask: without them the ray tests the whole scene to infinity.

Mouse picking turns a screen position into a ray: cam.ScreenPointToRay(Mouse.current.position.ReadValue()).

The query family

Query Shape Use
Physics.Raycast line bullets, line of sight, ground under the feet
Physics.SphereCast / CapsuleCast / BoxCast swept shape "would my character fit?", thick projectiles, forgiving aim assist
Physics.OverlapSphere / OverlapBox / OverlapCapsule volume, no movement explosions, "enemies within 10 m", melee hit boxes
Physics.CheckSphere volume, bool only cheap "is anything there?"
…NonAlloc variants, RaycastCommand same, into your array / batched as a job no garbage per call / thousands of rays

Warning: Physics.RaycastAll returns hits in no particular order. Sort by distance if you need the nearest first, or use RaycastNonAlloc with a reusable array and sort the filled part.

What a raycast computes: a model

The model fires a ray at spheres on different layers, filters by a layer mask, and keeps the nearest hit, which is what Physics.Raycast does (with a spatial acceleration structure instead of a loop):

csharp · try it yourself
using System;
using System.Collections.Generic;

var world = new List<Sphere>
{
    new("crate",  new V3(0, 0, 4),  0.5, Layer: 0),
    new("ghost",  new V3(0, 0, 6),  1.0, Layer: 9),   // a trigger-ish layer we want to ignore
    new("enemy",  new V3(0.4, 0, 9), 1.0, Layer: 7),
    new("wall",   new V3(0, 0, 15), 3.0, Layer: 6),
};

var origin = new V3(0, 0, 0);
var dir = new V3(0, 0, 1);

Fire("everything", ~0);
Fire("Enemy + Ground", (1 << 7) | (1 << 6));
Fire("Enemy only, 8 m", 1 << 7, 8);

void Fire(string label, int mask, double maxDistance = 100)
{
    Sphere? best = null; double bestT = double.MaxValue; V3 normal = default;
    foreach (var s in world)
    {
        if ((mask & (1 << s.Layer)) == 0) continue;               // layer mask filter
        double? t = Intersect(origin, dir, s);
        if (t is double d && d <= maxDistance && d < bestT) { best = s; bestT = d; normal = (origin + dir * d - s.Center).Normalized(); }
    }
    Console.WriteLine(best == null
        ? 
quot;{label,-16}: no hit" :
quot;{label,-16}: {best.Name} at distance {bestT:F2}, normal {normal}"); } static double? Intersect(V3 o, V3 d, Sphere s) // ray-sphere, d normalized { V3 oc = o - s.Center; double b = oc.Dot(d), c = oc.Dot(oc) - s.Radius * s.Radius; double disc = b * b - c; if (disc < 0) return null; double t = -b - Math.Sqrt(disc); return t >= 0 ? t : null; } record Sphere(string Name, V3 Center, double Radius, int Layer); readonly record struct V3(double X, double Y, double Z) { public static V3 operator +(V3 a, V3 b) => new(a.X + b.X, a.Y + b.Y, a.Z + b.Z); public static V3 operator -(V3 a, V3 b) => new(a.X - b.X, a.Y - b.Y, a.Z - b.Z); public static V3 operator *(V3 a, double k) => new(a.X * k, a.Y * k, a.Z * k); public double Dot(V3 b) => X * b.X + Y * b.Y + Z * b.Z; public V3 Normalized() { double l = Math.Sqrt(Dot(this)); return new(X / l, Y / l, Z / l); } public override string ToString() =>
quot;({X:F2}, {Y:F2}, {Z:F2})"; }
everything      : crate at distance 3.50, normal (0.00, 0.00, -1.00)
Enemy + Ground  : enemy at distance 8.08, normal (-0.40, 0.00, -0.92)
Enemy only, 8 m : no hit

The enemy is offset 0.4 to the side, so the ray grazes it and the normal tilts. The last query fails because the enemy is 8.08 m away, just beyond the 8 m limit.

Ground checks

Two common ways to know whether a character stands on something:

csharp
// 1. A short sphere cast down from the hips: forgiving on edges and small bumps.
bool grounded = Physics.SphereCast(transform.position + Vector3.up * 0.5f, 0.3f, Vector3.down,
                                   out RaycastHit ground, 0.6f, groundMask, QueryTriggerInteraction.Ignore);

// 2. CheckSphere at the feet: cheapest, no hit information.
bool grounded2 = Physics.CheckSphere(feet.position, 0.2f, groundMask, QueryTriggerInteraction.Ignore);

Use the hit normal to measure slope: Vector3.Angle(ground.normal, Vector3.up) gives the slope angle in degrees.

Debugging queries

  • Debug.DrawRay / Debug.DrawLine draw for one frame in the Scene view (and in the Game view with Gizmos enabled).
  • OnDrawGizmos / OnDrawGizmosSelected with Gizmos.DrawWireSphere show query volumes permanently in the editor.
  • The Physics Debugger window (Window > Analysis > Physics Debugger) shows every collider and lets you visualize queries.

Test yourself

Which query fits 'damage every enemy within 5 m of the explosion'?

  1. Raycast
  2. OverlapSphere (or its NonAlloc variant)
  3. SphereCast forward
  4. ScreenPointToRay

In what order does Physics.RaycastAll return its hits?

  1. Nearest first
  2. Farthest first
  3. No guaranteed order
  4. Alphabetical by name

Why pass a layer mask and a max distance to every raycast?

  1. They're required by the compiler
  2. They limit what the query tests and avoid hitting the wrong objects
  3. They make the ray thicker
  4. They enable interpolation