TExcelTAD
Home › Math for Games › Closest Point Queries

Closest Point Queries

"What is the nearest point on this shape to that point?" sounds academic, but it powers a surprising amount of gameplay: capsule collisions for characters, "snap the cursor to the nearest road", the minimum distance between a bullet's path and a player's head, magnetic aim assist, and the push-out step of most collision tests. Each shape has a short formula.

Closest point on a segment

A segment runs from A to B. Project P onto the line (the Projection lesson), then clamp the parameter to [0, 1] so the result stays between the end points:

text
t = clamp( dot(P - A, B - A) / dot(B - A, B - A), 0, 1 )
closest = A + (B - A) * t
cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>

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

Vec2 closestOnSegment(Vec2 p, Vec2 a, Vec2 b, double& t) {
    Vec2 ab = b - a;
    t = std::clamp(dot(p - a, ab) / dot(ab, ab), 0.0, 1.0);
    return a + ab * t;
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    Vec2 a{0, 0}, b{8, 4};                         // a road segment
    Vec2 cursors[] = {{4, 5}, {-3, 1}, {10, 6}, {6, 3}};
    for (Vec2 p : cursors) {
        double t;
        Vec2 c = closestOnSegment(p, a, b, t);
        Vec2 d = p - c;
        std::cout << "cursor (" << p.x << ", " << p.y << ") snaps to (" << c.x << ", " << c.y << ") t=" << t
                  << " distance " << std::sqrt(dot(d, d)) << "\n";
    }
}
cursor (4.000, 5.000) snaps to (5.200, 2.600) t=0.650 distance 2.683
cursor (-3.000, 1.000) snaps to (0.000, 0.000) t=0.000 distance 3.162
cursor (10.000, 6.000) snaps to (8.000, 4.000) t=1.000 distance 2.828
cursor (6.000, 3.000) snaps to (6.000, 3.000) t=0.750 distance 0.000

The second and third cursors are beyond the ends, so t is clamped and they snap to the end points.

Capsules

A capsule is all points within radius r of a segment: a cylinder with hemispherical caps. It is the standard shape for characters in every engine (Unity's CharacterController and CapsuleCollider, Unreal's UCapsuleComponent, Godot's CapsuleShape3D) because it slides smoothly over steps and edges and never snags on corners.

Testing a point or sphere against a capsule is "closest point on the segment, then a sphere test":

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

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}; }
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }

struct Capsule { Vec3 a, b; double r; };

bool sphereVsCapsule(Vec3 center, double radius, const Capsule& cap) {
    Vec3 ab = cap.b - cap.a;
    double t = std::clamp(dot(center - cap.a, ab) / dot(ab, ab), 0.0, 1.0);
    Vec3 closest = cap.a + ab * t;
    Vec3 d = center - closest;
    double rr = radius + cap.r;
    return dot(d, d) <= rr * rr;
}

int main() {
    std::cout << std::boolalpha;
    Capsule player{{0, 0.5, 0}, {0, 1.5, 0}, 0.5};         // 2 m tall, 0.5 m radius
    struct { const char* name; Vec3 c; double r; } balls[] = {
        {"at the knees  ", {0.8, 0.6, 0}, 0.4},
        {"above the head", {0, 2.3, 0}, 0.2},
        {"brushing hair ", {0, 2.1, 0}, 0.2},
        {"far away      ", {3, 1, 0}, 0.5},
    };
    for (auto& b : balls) std::cout << b.name << ": " << sphereVsCapsule(b.c, b.r, player) << "\n";
}
at the knees  : true
above the head: false
brushing hair : true
far away      : false

Closest points between two segments: did the bullet pass the head?

A fast bullet moves a long way in one frame. Treat its path during the frame as a segment and the target's head (moving too) as a capsule. The closest distance between two segments tells you whether the bullet came within the head's radius, which catches hits that frame-by-frame position checks miss ("tunneling").

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

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}; }
Vec3 operator+(Vec3 a, Vec3 b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; }
Vec3 operator*(Vec3 v, double s) { return {v.x * s, v.y * s, v.z * s}; }
double dot(Vec3 a, Vec3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; }

// Closest points between segments p1-q1 and p2-q2 (after Ericson, Real-Time Collision Detection).
double segmentDistance(Vec3 p1, Vec3 q1, Vec3 p2, Vec3 q2) {
    Vec3 d1 = q1 - p1, d2 = q2 - p2, r = p1 - p2;
    double a = dot(d1, d1), e = dot(d2, d2), f = dot(d2, r);
    double s, t;
    if (a < 1e-12 && e < 1e-12) { s = t = 0; }
    else if (a < 1e-12) { s = 0; t = std::clamp(f / e, 0.0, 1.0); }
    else {
        double c = dot(d1, r);
        if (e < 1e-12) { t = 0; s = std::clamp(-c / a, 0.0, 1.0); }
        else {
            double b = dot(d1, d2), denom = a * e - b * b;
            s = denom > 1e-12 ? std::clamp((b * f - c * e) / denom, 0.0, 1.0) : 0;
            t = (b * s + f) / e;
            if (t < 0) { t = 0; s = std::clamp(-c / a, 0.0, 1.0); }
            else if (t > 1) { t = 1; s = std::clamp((b - c) / a, 0.0, 1.0); }
        }
    }
    Vec3 c1 = p1 + d1 * s, c2 = p2 + d2 * t;
    Vec3 diff = c1 - c2;
    return std::sqrt(dot(diff, diff));
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    // This frame the bullet travels from z=0 to z=-30 (very fast), a little high and to the right.
    Vec3 bulletStart{0.12, 1.8, 0}, bulletEnd{0.12, 1.8, -30};
    // The head moved sideways during the frame, from x=-0.5 to x=0.5, at z=-20.
    Vec3 headStart{-0.5, 1.7, -20}, headEnd{0.5, 1.7, -20};
    const double headRadius = 0.15;

    double d = segmentDistance(bulletStart, bulletEnd, headStart, headEnd);
    std::cout << "closest approach " << d << " -> " << (d <= headRadius ? "HEADSHOT" : "miss") << "\n";

    // Checking only the end positions of the frame misses it completely:
    std::cout << "bullet end is " << 30 - 20 << " m past the head; a position-only check sees nothing\n";
}
closest approach 0.100 -> HEADSHOT
bullet end is 10 m past the head; a position-only check sees nothing

The segment-vs-segment test treats both motions as lines, which is an approximation (it ignores when each was where). Exact swept tests solve for the time of closest approach; the game-physics course covers continuous collision detection properly.

Closest point on a triangle and on a box

  • AABB: clamp each coordinate into the box (you met it in Circles and Spheres).
  • Oriented box: transform the point into the box's local space, clamp, transform back.
  • Triangle: project onto the triangle's plane, then if the point is outside, clamp to the nearest edge or vertex using barycentric tests. Ericson's Real-Time Collision Detection (chapter 5) has the canonical code for all of these.

Tip: Engines ship these queries: Unity's Collider.ClosestPoint and Physics.ClosestPoint, Unreal's UPrimitiveComponent::GetClosestPointOnCollision and FMath::ClosestPointOnSegment, Godot's Geometry3D.get_closest_point_to_segment. Write your own only for code that runs outside the physics engine.

Test yourself

Why clamp t to [0, 1] when finding the closest point on a segment?

  1. To normalize the segment
  2. So the result stays between the end points instead of on the infinite line
  3. To avoid negative distances
  4. It makes the result faster to compute

How do you test a sphere against a capsule?

  1. Compare the two radii
  2. Find the closest point on the capsule's segment, then do a sphere–sphere test with r1 + r2
  3. Use an AABB
  4. Raycast from the sphere

Why are capsules the usual character collider?

  1. They are the cheapest shape to render
  2. They slide smoothly over steps and edges without snagging
  3. They never collide
  4. They support non-uniform scale