Narrow Phase: GJK Distance
SAT needs a list of candidate axes, which is easy for boxes but grows quickly for general convex hulls (every face normal plus every pair of edges). The Gilbert–Johnson–Keerthi algorithm (GJK) takes a different route: it never looks at faces or edges at all. It only needs one function per shape, the support function, and it answers a more useful question than "do they overlap?": how far apart are they? That distance drives continuous collision detection, character controller skins and the speculative contacts most modern engines use. Box2D, Bullet, Jolt and PhysX all have a GJK at their core.
This lesson is a sketch: a working 2D GJK distance query you can read in one sitting, without the numerical hardening production code needs.
Minkowski difference
Take every point a of shape A and every point b of shape B and collect the differences a - b. That set is the Minkowski difference A ⊖ B. Two facts make it useful:
- A and B overlap exactly when two of their points are equal, that is when
A ⊖ Bcontains the origin. - The distance between A and B equals the distance from the origin to
A ⊖ B.
And the difference of two convex shapes is convex. So a collision question about two shapes becomes a simpler question about one convex shape and a point.
Support functions
You never build A ⊖ B explicitly. GJK only asks: what is the point of a shape that is farthest in direction d? That is the support function. For the difference it is simply support_A(d) - support_B(-d).
| Shape | support(d) |
|---|---|
| polygon / convex hull | the vertex with the largest dot(v, d) |
| circle / sphere | centre + radius * normalize(d) |
| box (OBB) | c ± e0·u0 ± e1·u1, picking each sign from dot(u, d) |
| capsule | the support of the segment, plus radius * normalize(d) |
So adding a new shape to a GJK-based engine means writing one small function, and any pair of supported shapes works with any other. Here are a few support points, including the difference of a box and a triangle:
#include <iostream>
#include <iomanip>
#include <vector>
#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) { return {-a.x, -a.y}; }
double dot(Vec2 a, Vec2 b) { return a.x * b.x + a.y * b.y; }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec2 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ")"; }
Vec2 supportPoly(const std::vector<Vec2>& poly, Vec2 d) {
Vec2 best = poly[0];
for (Vec2 v : poly) if (dot(v, d) > dot(best, d)) best = v;
return best;
}
Vec2 supportCircle(Vec2 c, double r, Vec2 d) {
double len = std::sqrt(dot(d, d));
return {c.x + r * d.x / len, c.y + r * d.y / len};
}
int main() {
std::cout << std::fixed << std::setprecision(3);
std::vector<Vec2> box{{-1, -1}, {1, -1}, {1, 1}, {-1, 1}};
std::vector<Vec2> tri{{3, 0.5}, {5, 2}, {3.5, 3}};
for (Vec2 d : {Vec2{1, 0}, Vec2{-1, 0}, Vec2{1, 1}, Vec2{0, -1}}) {
std::cout << "d = " << d << ": box " << supportPoly(box, d) << ", circle "
<< supportCircle({0, 4}, 1, d) << ", box - tri " << supportPoly(box, d) - supportPoly(tri, -d) << "\n";
}
}d = (1.000, 0.000): box (1.000, -1.000), circle (1.000, 4.000), box - tri (-2.000, -1.500)
d = (-1.000, 0.000): box (-1.000, -1.000), circle (-1.000, 4.000), box - tri (-6.000, -3.000)
d = (1.000, 1.000): box (1.000, 1.000), circle (0.707, 4.707), box - tri (-2.000, 0.500)
d = (0.000, -1.000): box (-1.000, -1.000), circle (0.000, 3.000), box - tri (-4.500, -4.000)
The box - tri column is a set of points on the boundary of the Minkowski difference. In direction (1, 0) the farthest it reaches is x = -2: the whole difference lies to the left of the origin, so the box and the triangle can't overlap. That single support point already proves they are at least 2 apart along x.
The GJK loop
GJK keeps a simplex: up to 3 points of A ⊖ B in 2D (up to 4 in 3D). Each iteration:
- Find the point of the simplex closest to the origin, and drop the simplex points that don't contribute to it (a point, a segment or a triangle).
- If that closest point is the origin itself (the triangle contains it), the shapes overlap.
- Otherwise search in the direction from the closest point toward the origin,
d = -closest, and get a new support pointw. - If
wgets no closer to the origin than the current closest point alongd, nothing better exists: the current distance is the answer. Otherwise addwto the simplex and repeat.
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <functional>
#include <algorithm>
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; }
double cross(Vec2 a, Vec2 b) { return a.x * b.y - a.y * b.x; }
double z0(double v) { return std::fabs(v) < 5e-4 ? 0.0 : v; }
std::ostream& operator<<(std::ostream& os, Vec2 v) { return os << "(" << z0(v.x) << ", " << z0(v.y) << ")"; }
using Support = std::function<Vec2(Vec2)>;
Support polygon(std::vector<Vec2> pts) {
return [pts](Vec2 d) { Vec2 b = pts[0]; for (Vec2 v : pts) if (dot(v, d) > dot(b, d)) b = v; return b; };
}
// Closest point to the origin on segment ab; reduces `simplex` to the points that matter.
Vec2 closestOnSegment(Vec2 a, Vec2 b, std::vector<Vec2>& simplex) {
Vec2 ab = b - a;
double t = -dot(a, ab) / dot(ab, ab);
if (t <= 0) { simplex = {a}; return a; }
if (t >= 1) { simplex = {b}; return b; }
simplex = {a, b};
return a + ab * t;
}
Vec2 closestOnSimplex(std::vector<Vec2>& s) {
if (s.size() == 1) return s[0];
if (s.size() == 2) return closestOnSegment(s[0], s[1], s);
// triangle: origin inside?
double c1 = cross(s[1] - s[0], Vec2{0, 0} - s[0]), c2 = cross(s[2] - s[1], Vec2{0, 0} - s[1]),
c3 = cross(s[0] - s[2], Vec2{0, 0} - s[2]);
if ((c1 >= 0 && c2 >= 0 && c3 >= 0) || (c1 <= 0 && c2 <= 0 && c3 <= 0)) return {0, 0};
// otherwise the closest point lies on one of the three edges
std::vector<Vec2> best, tmp;
Vec2 bestP{0, 0};
double bestD = 1e300;
int edges[3][2] = {{0, 1}, {1, 2}, {2, 0}};
for (auto& e : edges) {
Vec2 p = closestOnSegment(s[e[0]], s[e[1]], tmp);
if (dot(p, p) < bestD) { bestD = dot(p, p); bestP = p; best = tmp; }
}
s = best;
return bestP;
}
double gjkDistance(const Support& A, const Support& B, bool verbose) {
auto support = [&](Vec2 d) { return A(d) - B(d * -1); };
std::vector<Vec2> simplex{support({1, 0})};
for (int iter = 1; iter <= 20; iter++) {
Vec2 c = closestOnSimplex(simplex);
double dist = std::sqrt(dot(c, c));
if (verbose) std::cout << " iter " << iter << ": simplex size " << simplex.size()
<< ", closest " << c << ", distance " << dist << "\n";
if (dist < 1e-9) return 0; // origin inside: overlap
Vec2 d = c * -1;
Vec2 w = support(d);
if (dot(c, c) - dot(c, w) < 1e-9 * dot(c, c)) return dist; // no progress: converged
simplex.push_back(w);
}
return -1;
}
int main() {
std::cout << std::fixed << std::setprecision(3);
Support box = polygon({{-1, -1}, {1, -1}, {1, 1}, {-1, 1}});
Support tri = polygon({{3, 0.5}, {5, 2}, {3.5, 3}});
std::cout << "box vs triangle:\n";
double d1 = gjkDistance(box, tri, true);
std::cout << " distance = " << d1 << "\n";
Support tilted = polygon({{2.2, 1.6}, {4, 4}, {1.5, 3.5}});
std::cout << "box vs tilted triangle:\n";
double d2 = gjkDistance(box, tilted, true);
std::cout << " distance = " << d2 << "\n";
// A circle is "a point with a radius": run GJK on its centre, then subtract the radius.
Support centre = polygon({{0, 4}});
double r = 1;
std::cout << "box vs circle (r=1 at (0, 4)): distance = " << gjkDistance(box, centre, false) - r << "\n";
Support overlapping = polygon({{0.5, 0.5}, {2.5, 0.8}, {1, 2.5}});
std::cout << "box vs overlapping triangle: distance = " << gjkDistance(box, overlapping, false) << "\n";
}box vs triangle:
iter 1: simplex size 1, closest (-2.000, -1.500), distance 2.500
iter 2: simplex size 2, closest (-2.000, 0.000), distance 2.000
distance = 2.000
box vs tilted triangle:
iter 1: simplex size 1, closest (-0.500, -4.500), distance 4.528
iter 2: simplex size 1, closest (-1.200, -0.600), distance 1.342
distance = 1.342
box vs circle (r=1 at (0, 4)): distance = 2.000
box vs overlapping triangle: distance = 0.000
Each line shows the simplex moving toward the feature of A ⊖ B nearest to the origin. For the first triangle the final simplex is a segment: the closest features are an edge of the box (x = 1) and the triangle's left vertex, 2 apart. For the tilted triangle it is a single point, (-1.2, -0.6): the closest features are two vertices, the box corner (1, 1) and the triangle corner (2.2, 1.6), and the distance is √(1.2² + 0.6²) = 1.342. GJK usually converges in a handful of iterations, even for hulls with dozens of vertices, because each support call jumps straight to the best vertex in the new direction.
Tip: The circle case is how engines treat rounded shapes: spheres, capsules and Box2D's rounded polygons are a "core" shape plus a radius. GJK works on the cores, and the radius is subtracted at the end. It is faster and more robust than running GJK on a curved support function.
What GJK doesn't give you: EPA
When the shapes overlap, GJK only says "distance 0". It doesn't say how deep or along which normal, and the solver needs both. Two common answers:
- EPA (Expanding Polytope Algorithm): start from GJK's final simplex, which contains the origin, and repeatedly push out the face of the polytope closest to the origin with a new support point. When the closest face stops moving, its normal is the contact normal and its distance is the penetration depth.
- Avoid deep overlap altogether: keep shapes slightly apart with a small margin (a "skin"), so most contacts are found while GJK still reports a positive distance and the witness points give the normal directly. Jolt (with its "convex radius") and Box2D (with rounded polygons and speculative contacts) both use this idea, and fall back to EPA or SAT-style tests for the cases where shapes really do overlap.
Test yourself
Two convex shapes A and B overlap exactly when…
- their support points are equal in every direction
- their Minkowski difference contains the origin
- their centres are closer than 1
- GJK needs more than 3 iterations
What is the support point of the Minkowski difference A ⊖ B in direction d?
- support_A(d) + support_B(d)
- support_A(d) - support_B(-d)
- support_A(-d) - support_B(d)
- the centre of A minus the centre of B
GJK reports distance 0 for two overlapping hulls. What do engines use to get the penetration normal and depth?
- Run GJK again with a bigger simplex
- EPA, or keep a small margin so contacts are found before overlap
- The broad phase AABBs
- Nothing; overlapping shapes are ignored