TExcelTAD
Home › Math for Games › Ray–Triangle

Ray–Triangle

Game meshes are made of triangles, so the most precise raycast is a ray against a triangle. Mesh colliders, terrain picking, decal placement, bullet holes, and every GPU and CPU ray tracer rely on it. The standard algorithm is Möller–Trumbore (1997): fast, needs no precomputed plane, and returns the hit distance plus barycentric coordinates, which tell you where inside the triangle the hit is.

Barycentric coordinates

Any point on a triangle A, B, C can be written as

text
P = (1 - u - v) A + u B + v C          with u >= 0, v >= 0, u + v <= 1

u and v are how far toward B and C the point lies. If any of the three weights (1-u-v, u, v) is negative, the point is outside the triangle. The weights are also exactly what you use to interpolate vertex data at the hit: UV coordinates for a decal, vertex colors, or smooth normals.

Möller–Trumbore

The idea: solve origin + t * dir = (1-u-v) A + u B + v C for t, u, v at once using cross and dot products (Cramer's rule in disguise).

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

struct Vec3 { double x, y, z; };
Vec3 operator-(Vec3 a, Vec3 b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }
Vec3 cross(Vec3 a, Vec3 b) { return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; }

struct Hit { double t, u, v; };

std::optional<Hit> rayTriangle(Vec3 orig, Vec3 dir, Vec3 a, Vec3 b, Vec3 c) {
    const double EPS = 1e-9;
    Vec3 e1 = b - a, e2 = c - a;
    Vec3 p = cross(dir, e2);
    double det = dot(e1, p);
    if (std::fabs(det) < EPS) return std::nullopt;     // ray parallel to the triangle
    double inv = 1 / det;
    Vec3 s = orig - a;
    double u = dot(s, p) * inv;
    if (u < 0 || u > 1) return std::nullopt;
    Vec3 q = cross(s, e1);
    double v = dot(dir, q) * inv;
    if (v < 0 || u + v > 1) return std::nullopt;
    double t = dot(e2, q) * inv;
    if (t < EPS) return std::nullopt;                  // behind the origin
    return Hit{t, u, v};
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    // A triangle standing in the z = -5 plane.
    Vec3 A{0, 0, -5}, B{4, 0, -5}, C{0, 4, -5};
    struct { const char* name; Vec3 o; } rays[] = {
        {"near corner A", {0.1, 0.1, 0}},
        {"middle       ", {1, 1, 0}},
        {"near B       ", {3.8, 0.1, 0}},
        {"outside      ", {3, 3, 0}},
    };
    for (auto& r : rays) {
        auto h = rayTriangle(r.o, {0, 0, -1}, A, B, C);
        std::cout << r.name << ": ";
        if (!h) { std::cout << "miss\n"; continue; }
        std::cout << "t=" << h->t << "  weights A=" << 1 - h->u - h->v << " B=" << h->u << " C=" << h->v << "\n";
    }
}
near corner A: t=5.000  weights A=0.950 B=0.025 C=0.025
middle       : t=5.000  weights A=0.500 B=0.250 C=0.250
near B       : t=5.000  weights A=0.025 B=0.950 C=0.025
outside      : miss

(3, 3) misses because u + v = 1.5 > 1: it lies beyond the hypotenuse.

Interpolating vertex data

With the weights, anything stored at the vertices can be blended at the hit point. Here each vertex has a color and a UV coordinate, and a bullet hole decal needs both:

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

struct Vertex { double r, g, b; double uvx, uvy; };

int main() {
    std::cout << std::fixed << std::setprecision(3);
    Vertex A{1, 0, 0, 0, 0}, B{0, 1, 0, 1, 0}, C{0, 0, 1, 0, 1};
    double u = 0.25, v = 0.5, w = 1 - u - v;            // from a ray hit

    double r = w * A.r + u * B.r + v * C.r;
    double g = w * A.g + u * B.g + v * C.g;
    double b = w * A.b + u * B.b + v * C.b;
    double uvx = w * A.uvx + u * B.uvx + v * C.uvx;
    double uvy = w * A.uvy + u * B.uvy + v * C.uvy;
    std::cout << "color at hit: (" << r << ", " << g << ", " << b << ")\n";
    std::cout << "uv at hit:    (" << uvx << ", " << uvy << ")\n";
}
color at hit: (0.250, 0.250, 0.500)
uv at hit:    (0.250, 0.500)

This is exactly what the GPU does for every pixel of every triangle: the rasterizer computes barycentric weights per pixel and interpolates the vertex shader's outputs with them. Unity returns these weights from a mesh-collider raycast as RaycastHit.barycentricCoordinate (and RaycastHit.textureCoord already interpolated).

Back-face culling for rays

The sign of det tells you which side the ray came from: positive when the ray hits the side where the vertices appear counter-clockwise (the front, with this winding), negative from behind. Raycasts often ignore back faces, so a ray that starts inside a closed mesh doesn't immediately hit the inside of its walls. Change one line to cull:

text
if (det < EPS) return nullopt;     // instead of fabs(det) < EPS

Many triangles

A character mesh has tens of thousands of triangles; testing them all for every bullet is too slow. Engines put triangles in a bounding volume hierarchy (BVH): a tree of AABBs. A ray first tests the root box, then only descends into children whose boxes it hits. That turns thousands of triangle tests into a few dozen box tests and a handful of triangle tests. The game-engine course builds one; physics engines (PhysX, Jolt, Chaos) and libraries like three-mesh-bvh ship optimized versions.

Tip: Collision meshes should be much simpler than render meshes. A wall that renders with 5,000 triangles should collide as a box. Simple colliders are faster and give players smoother, more predictable movement.

Test yourself

Barycentric weights of a hit are (0.2, 0.5, 0.3). Is the point inside the triangle?

  1. Yes, all weights are between 0 and 1 and sum to 1
  2. No, the weights must be equal
  3. No, a weight above 0.4 means outside
  4. Only if t is negative

What does a near-zero det mean in Möller–Trumbore?

  1. A hit at the corner
  2. The ray is parallel to the triangle's plane
  3. The triangle is very large
  4. The hit is behind the camera

How do engines avoid testing every triangle of a big mesh?

  1. They test only the first triangle
  2. A bounding volume hierarchy (tree of boxes) skips whole groups of triangles
  3. They use Euler angles
  4. They lower the frame rate