TExcelTAD
Home › Game Physics & Animation › Raycasts, Shape Casts and Overlaps

Raycasts, Shape Casts and Overlaps

Not everything in a game is a simulated body. Gameplay code constantly asks the physics world questions: what does the crosshair point at, is there ground under the player's feet, which enemies are inside the explosion radius, can the AI see the player? These are scene queries. They use the same broad-phase structures as the simulation (usually the BVH) and the same narrow-phase math, but they don't create contacts or move anything.

Query Question Typical uses
Raycast What does this ray hit first, and where? hitscan weapons, line of sight, mouse picking, ground checks
Shape cast (sweep) If I move this sphere/capsule/box along a path, where does it first touch something? character movement, thick projectiles, camera collision
Overlap Which colliders intersect this shape right now? explosions, triggers, "is this spot free to spawn?"

Ray vs AABB: the slab test

Every BVH raycast starts with ray vs box tests on the tree nodes, so this one has to be fast. Think of an AABB as the intersection of three slabs (two in 2D): the space between minX and maxX, between minY and maxY, and so on. The ray enters and leaves each slab at parameters t = (min - origin) / dir and t = (max - origin) / dir. The ray is inside the box where it is inside all slabs at once: from the latest entry to the earliest exit.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <limits>

struct Vec2 { double x, y; };
struct AABB { Vec2 min, max; };

// Returns the entry distance t along the ray, or -1 if it misses. dir need not be unit length.
double rayAABB(Vec2 o, Vec2 d, const AABB& b, double maxT) {
    double tEnter = 0, tExit = maxT;
    const double inf = std::numeric_limits<double>::infinity();
    double invX = d.x != 0 ? 1 / d.x : inf, invY = d.y != 0 ? 1 / d.y : inf;
    double t1 = (b.min.x - o.x) * invX, t2 = (b.max.x - o.x) * invX;
    if (d.x == 0) { if (o.x < b.min.x || o.x > b.max.x) return -1; }       // parallel and outside the slab
    else { tEnter = std::max(tEnter, std::min(t1, t2)); tExit = std::min(tExit, std::max(t1, t2)); }
    double t3 = (b.min.y - o.y) * invY, t4 = (b.max.y - o.y) * invY;
    if (d.y == 0) { if (o.y < b.min.y || o.y > b.max.y) return -1; }
    else { tEnter = std::max(tEnter, std::min(t3, t4)); tExit = std::min(tExit, std::max(t3, t4)); }
    return tEnter <= tExit ? tEnter : -1;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    AABB crate{{4, 1}, {6, 3}};
    struct Case { const char* label; Vec2 o, d; double maxT; } cases[] = {
        {"straight at it      ", {0, 2}, {1, 0}, 100},
        {"diagonal, hits      ", {0, 0}, {1, 0.5}, 100},
        {"diagonal, misses    ", {0, 0}, {1, 1}, 100},
        {"pointing away       ", {0, 2}, {-1, 0}, 100},
        {"starts inside       ", {5, 2}, {1, 0}, 100},
        {"too short (max 3)   ", {0, 2}, {1, 0}, 3},
    };
    for (const Case& c : cases) {
        double t = rayAABB(c.o, c.d, crate, c.maxT);
        std::cout << c.label << ": ";
        if (t < 0) std::cout << "miss\n";
        else std::cout << "hit at t = " << t << ", point (" << c.o.x + c.d.x * t << ", " << c.o.y + c.d.y * t << ")\n";
    }
}
straight at it      : hit at t = 4.000, point (4.000, 2.000)
diagonal, hits      : hit at t = 4.000, point (4.000, 2.000)
diagonal, misses    : miss
pointing away       : miss
starts inside       : hit at t = 0.000, point (5.000, 2.000)
too short (max 3)   : miss

Three details matter in real code:

  • tEnter starts at 0, so a ray that starts inside the box reports t = 0. Engines differ here: Unity's Physics.Raycast doesn't report colliders the ray starts inside, and Godot only does when hit_from_inside is enabled on the query. That is a common cause of "my ground check fails when I'm slightly sunk into the floor".
  • maxT limits the ray's length. Every engine raycast takes a maximum distance; always pass a sensible one instead of infinity, because the broad phase can prune much more.
  • Production versions precompute 1 / dir once per ray (it is reused for every BVH node) and rely on IEEE infinities instead of the d == 0 branches.

For spheres, see ray–sphere; for meshes, ray–triangle.

Shape casts are rays against inflated shapes

A sphere cast asks where a sphere of radius r, moving along a ray, first touches a shape. That is the same as a ray (the sphere's centre) against the target shape inflated by r, its Minkowski sum with the sphere. Against a sphere of radius R the inflated shape is a sphere of radius R + r, so a sphere cast is a ray–sphere test with a bigger radius:

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cmath>

struct Vec2 { double x, y; };
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }

// Unit-length ray direction d. Returns hit distance or -1.
double raySphere(Vec2 o, Vec2 d, Vec2 c, double radius) {
    Vec2 m{o.x - c.x, o.y - c.y};
    double b = dot(m, d), cc = dot(m, m) - radius * radius;
    if (cc > 0 && b > 0) return -1;              // outside and pointing away
    double disc = b * b - cc;
    if (disc < 0) return -1;
    return std::fmax(0.0, -b - std::sqrt(disc));
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    Vec2 pillar{10, 1.5};
    double pillarR = 1.0;
    Vec2 o{0, 0}, d{1, 0};
    std::cout << "thin ray (bullet): " << (raySphere(o, d, pillar, pillarR) < 0 ? "miss" : "hit") << "\n";
    for (double r : {0.3, 0.6, 1.0}) {
        double t = raySphere(o, d, pillar, pillarR + r);   // sphere cast = ray vs inflated sphere
        std::cout << "sphere cast, radius " << r << ": ";
        if (t < 0) std::cout << "miss\n";
        else std::cout << "hits at distance " << t << ", centre stops at x = " << o.x + d.x * t << "\n";
    }
}
thin ray (bullet): miss
sphere cast, radius 0.300: miss
sphere cast, radius 0.600: hits at distance 9.443, centre stops at x = 9.443
sphere cast, radius 1.000: hits at distance 8.677, centre stops at x = 8.677

The bullet passes 0.5 below the pillar's edge and misses, and so does a sphere of radius 0.3. A sphere of radius 0.6 moving along the same line clips the pillar's lower edge, and a sphere of radius 1 hits it even earlier. This is why character movement uses capsule casts, not rays: a ray from the character's centre would let its shoulders pass through door frames. Inflating a box by a sphere gives a rounded box, which is why engines implement box and capsule casts with dedicated sweep routines or with conservative advancement: measure the distance to the target with GJK, move the shape forward by that much (it can't hit anything closer), and repeat until the distance is nearly zero.

Fast bullets: one raycast per step

A real bullet travels hundreds of meters per second. As a rigid body it would tunnel through every wall. The standard approach: keep the bullet as plain data (position, velocity), and each physics step cast a ray from the old position to the new one. The first hit along that segment is the impact, and nothing can be skipped, however fast the bullet is. It is also much cheaper than a CCD-enabled body.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdint>

struct Target { std::string name; double minX, maxX; uint32_t layer; };
enum : uint32_t { World = 1, Enemy = 2, Friendly = 4, Glass = 8 };

int main() {
    std::cout << std::fixed << std::setprecision(3);
    // 1D range for clarity: targets are slabs along the bullet's path
    std::vector<Target> targets = {
        {"window",   30.0, 30.02, Glass},
        {"ally",     45.0, 45.4,  Friendly},
        {"thin wall",61.0, 61.1,  World},
        {"enemy",    80.0, 80.5,  Enemy},
    };
    const uint32_t mask = World | Enemy;           // bullets ignore glass panes and allies
    double x = 0, v = 900;                         // 900 m/s
    const double dt = 1.0 / 60;
    for (int step = 1; step <= 10; step++) {
        double next = x + v * dt;
        const Target* best = nullptr;
        for (const Target& t : targets) {
            if (!(t.layer & mask)) continue;                         // layer filter
            if (t.minX >= x && t.minX <= next && (!best || t.minX < best->minX)) best = &t;
        }
        std::cout << "step " << step << ": ray " << x << " -> " << next;
        if (best) { std::cout << "  hit " << best->name << " at " << best->minX << "\n"; break; }
        std::cout << "\n";
        x = next;
    }
}
step 1: ray 0.000 -> 15.000
step 2: ray 15.000 -> 30.000
step 3: ray 30.000 -> 45.000
step 4: ray 45.000 -> 60.000
step 5: ray 60.000 -> 75.000  hit thin wall at 61.000

Each step covers 15 m, far more than the wall's 0.1 m, yet the ray finds it. The layer mask lets the bullet fly through the window and the ally, the same filtering as in the collision pipeline. Add gravity and drag to the velocity each step and you have ballistic bullets; set dt to the whole range at once and you have a classic hitscan weapon.

Queries in engines

csharp
// Unity 6
int mask = LayerMask.GetMask("World", "Enemy");
if (Physics.Raycast(muzzle.position, muzzle.forward, out RaycastHit hit, 200f, mask))
    Debug.Log(
quot;hit {hit.collider.name} at {hit.point}, normal {hit.normal}"); if (Physics.SphereCast(transform.position, 0.4f, Vector3.down, out RaycastHit ground, 1.2f, mask)) Debug.Log(
quot;ground {ground.distance:F2} m below"); Collider[] inBlast = Physics.OverlapSphere(explosionPos, 5f, mask);
cpp
// Unreal Engine 5
FHitResult Hit;
FCollisionQueryParams Params(SCENE_QUERY_STAT(WeaponTrace), /*bTraceComplex*/ false, /*IgnoreActor*/ this);
if (GetWorld()->LineTraceSingleByChannel(Hit, Start, End, ECC_Visibility, Params))
{
    UE_LOG(LogTemp, Log, TEXT("Hit %s"), *GetNameSafe(Hit.GetActor()));
}
FHitResult Sweep;
GetWorld()->SweepSingleByChannel(Sweep, Start, End, FQuat::Identity, ECC_Pawn,
                                 FCollisionShape::MakeSphere(30.f), Params);   // centimetres
gdscript
# Godot 4
var space := get_world_3d().direct_space_state
var query := PhysicsRayQueryParameters3D.create(from, to, collision_mask)
query.exclude = [self]
var hit := space.intersect_ray(query)
if hit:
    print(hit.collider, " at ", hit.position, " normal ", hit.normal)

Tip: Draw your queries while debugging: a line for each ray (green for miss, red to the hit point) and a wire sphere for casts and overlaps. Most "the raycast doesn't work" bugs are a wrong direction, a ray that is too short, a ray starting inside the floor, or a layer mask that excludes the target. Unity's Debug.DrawRay, Unreal's DrawDebugLine and Godot's visible collision shapes make them visible in seconds.

Test yourself

In the slab test, when does the ray hit the box?

  1. When it enters any slab
  2. When the latest slab entry comes before the earliest slab exit
  3. When the ray is parallel to an axis
  4. When the origin is outside the box

A sphere cast of radius r against a sphere of radius R is equivalent to…

  1. a ray against a sphere of radius R - r
  2. a ray against a sphere of radius R + r
  3. an overlap test at the end point
  4. two separate raycasts

Why do games usually implement fast bullets as a raycast from the old to the new position each step?

  1. Rays look better
  2. The ray covers the whole path, so nothing is skipped however fast the bullet moves, and it is cheaper than a CCD rigid body
  3. Rigid bodies can't move fast
  4. Raycasts ignore layers