TExcelTAD
Home › Game Physics & Animation › Narrow Phase: SAT for Oriented Boxes

Narrow Phase: SAT for Oriented Boxes

The broad phase hands the narrow phase a short list of pairs whose bounding boxes overlap. Now the question is exact: do the real shapes touch, and if so, along which normal and how deep? The physics solver needs both, because the normal says which way to push and the depth says how far.

For boxes the standard tool is the separating axis theorem. The SAT lesson in Math for Games proves the idea for general convex polygons; this lesson specializes it to oriented bounding boxes (OBBs), where it becomes very cheap, and turns the result into a contact normal.

An OBB in 2D

An OBB is a centre c, two unit axes u0 and u1 (the box's local x and y directions after rotation), and two half extents e0 and e1. You never need its corners to project it: the projection of the box onto an axis L is an interval centred on dot(c, L) with radius

text
r = e0 * |dot(u0, L)| + e1 * |dot(u1, L)|

Two boxes are separated on L if the distance between their centres along L is larger than the sum of their radii. In 2D the only candidate axes are the 2 axes of each box, so 4 tests in total.

Penetration depth and contact normal

If no axis separates the boxes, each axis has an overlap rA + rB - |dot(cB - cA, L)|. The axis with the smallest overlap is the cheapest way out: that axis is the contact normal and the overlap is the penetration depth. Flip the normal if needed so it points from A toward B, which is the convention most solvers use.

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

struct Vec2 { double x, y; };
Vec2 operator-(Vec2 a, Vec2 b) { return {a.x - b.x, a.y - b.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; }

struct OBB {
    Vec2 c; double e0, e1; Vec2 u0, u1;
    OBB(Vec2 centre, double hx, double hy, double deg) : c(centre), e0(hx), e1(hy) {
        double a = deg * 3.141592653589793 / 180;
        u0 = {std::cos(a), std::sin(a)};
        u1 = {-std::sin(a), std::cos(a)};
    }
    double radius(Vec2 L) const { return e0 * std::fabs(dot(u0, L)) + e1 * std::fabs(dot(u1, L)); }
};

struct Contact { bool hit; Vec2 normal; double depth; };

Contact satOBB(const OBB& A, const OBB& B) {
    Vec2 d = B.c - A.c;
    Contact best{true, {0, 0}, std::numeric_limits<double>::max()};
    for (Vec2 L : {A.u0, A.u1, B.u0, B.u1}) {
        double dist = std::fabs(dot(d, L));
        double overlap = A.radius(L) + B.radius(L) - dist;
        if (overlap < 0) return {false, L, overlap};      // separating axis found: early out
        if (overlap < best.depth) {
            best.depth = overlap;
            best.normal = dot(d, L) < 0 ? Vec2{-L.x, -L.y} : L;   // point from A to B
        }
    }
    return best;
}

void report(const char* label, const OBB& A, const OBB& B) {
    Contact c = satOBB(A, B);
    std::cout << label << ": ";
    if (!c.hit) { std::cout << "separated (gap " << -c.depth << " on axis (" << z0(c.normal.x) << ", " << z0(c.normal.y) << "))\n"; return; }
    std::cout << "touching, normal (" << z0(c.normal.x) << ", " << z0(c.normal.y) << "), depth " << c.depth << "\n";
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    OBB ground({0, -1}, 10, 1, 0);                       // a flat floor, top at y = 0
    report("crate resting 0.05 deep ", ground, OBB({2, 0.45}, 0.5, 0.5, 0));
    report("crate tilted 30 degrees ", ground, OBB({2, 0.6}, 0.5, 0.5, 30));
    report("crate hovering          ", ground, OBB({2, 0.8}, 0.5, 0.5, 30));
    report("two rotated crates      ", OBB({0, 0}, 1, 0.5, 20), OBB({1.3, 0.8}, 0.5, 0.5, -10));
}
crate resting 0.05 deep : touching, normal (0.000, 1.000), depth 0.050
crate tilted 30 degrees : touching, normal (0.000, 1.000), depth 0.083
crate hovering          : separated (gap 0.117 on axis (0.000, 1.000))
two rotated crates      : touching, normal (0.940, 0.342), depth 0.188

The first two results point straight up (0, 1), the floor's normal, as you'd expect for crates on the ground. The tilted crate's corner reaches below y = 0: its radius along (0, 1) is 0.5·cos30° + 0.5·sin30° = 0.683, so a centre at 0.6 means a depth of 0.083. The hovering crate is the same box 0.2 higher, and SAT reports a 0.117 gap. In the last pair the winning axis is (0.940, 0.342), the first crate's own x axis rotated by 20°: the shortest way out is along a tilted direction, not straight up or sideways.

Note: A normal and a depth are enough for simple solvers (and for the positional correction lesson), but box stacks also need contact points: one or two points where the boxes touch. Engines find them by clipping the "incident" face of one box against the side planes of the "reference" face of the other (Sutherland–Hodgman clipping). Box2D's polygon manifold code is a readable example.

Watch out for near-parallel ties

Look at the first result again: the crate sits flat on the floor, and the floor's up axis and the crate's up axis are the same direction. Both give the same overlap, and floating-point rounding decides which one wins. When the two candidate normals belong to different boxes, a tiny change of angle can flip the choice from frame to frame, and the contact normal and contact points jump with it: stacks jitter. Engines add a bias toward the reference face they chose in the previous frame (for example "only switch if the new axis is better by more than 5%"), and many prefer face axes of the first box when overlaps are equal.

SAT for 3D boxes: 15 axes

In 3D, two convex polyhedra can be separated by a face normal of either shape or by a direction perpendicular to one edge of each shape. For two OBBs that gives:

Candidate axes Count
A's 3 face normals 3
B's 3 face normals 3
cross(A.axis[i], B.axis[j]) for every pair 9
total 15

The edge-edge axes catch the case of two boxes rotated so that their edges cross like an X: no face normal separates them, but a cross product does. When two edges are parallel the cross product is zero; skip that axis (a zero axis would report a false "overlap" or divide by zero once normalized).

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

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 OBB3 { Vec3 c; Vec3 u[3]; double e[3]; };

double radius(const OBB3& b, Vec3 L) {
    return b.e[0] * std::fabs(dot(b.u[0], L)) + b.e[1] * std::fabs(dot(b.u[1], L)) + b.e[2] * std::fabs(dot(b.u[2], L));
}

// Returns the name of the first separating axis, or "" if the boxes overlap.
std::string separatingAxis(const OBB3& A, const OBB3& B) {
    Vec3 d = B.c - A.c;
    auto separates = [&](Vec3 L) {
        if (dot(L, L) < 1e-12) return false;               // parallel edges: skip
        return std::fabs(dot(d, L)) > radius(A, L) + radius(B, L);
    };
    const char* names = "xyz";
    for (int i = 0; i < 3; i++) if (separates(A.u[i])) return std::string("A face ") + names[i];
    for (int i = 0; i < 3; i++) if (separates(B.u[i])) return std::string("B face ") + names[i];
    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 3; j++)
            if (separates(cross(A.u[i], B.u[j]))) return std::string("edge A") + names[i] + " x B" + names[j];
    return "";
}

OBB3 boxRotated(Vec3 c, double ex, double ey, double ez, Vec3 axis, double deg) {
    // rotation by deg around a unit axis (Rodrigues), applied to the world axes
    double a = deg * 3.141592653589793 / 180, cs = std::cos(a), sn = std::sin(a);
    auto rot = [&](Vec3 v) {
        Vec3 k = axis, kv = cross(k, v);
        double kd = dot(k, v);
        return Vec3{v.x * cs + kv.x * sn + k.x * kd * (1 - cs), v.y * cs + kv.y * sn + k.y * kd * (1 - cs),
                    v.z * cs + kv.z * sn + k.z * kd * (1 - cs)};
    };
    return {c, {rot({1, 0, 0}), rot({0, 1, 0}), rot({0, 0, 1})}, {ex, ey, ez}};
}

int main() {
    // Two long beams with a diamond cross-section, crossing like an X:
    // A lies along x (rotated 45 degrees around x), B lies along z (rotated 45 degrees around z) above it.
    OBB3 A = boxRotated({0, 0, 0}, 3, 0.5, 0.5, {1, 0, 0}, 45);
    for (double h : {1.5, 1.3}) {
        OBB3 B = boxRotated({0, h, 0}, 0.5, 0.5, 3, {0, 0, 1}, 45);
        std::string axis = separatingAxis(A, B);
        std::cout << std::fixed << std::setprecision(2) << "B at height " << h << ": "
                  << (axis.empty() ? "overlap" : "separated by " + axis) << "\n";
    }
}
B at height 1.50: separated by edge Ax x Bz
B at height 1.30: overlap

At height 1.5 none of the six face normals separates the beams; only the cross product of A's long axis (x) and B's long axis (z), which is the world y axis, does. Each diamond reaches 0.5·√2 ≈ 0.707 toward the other along y, so they meet when the centres are 1.414 apart. A 3D OBB test that checked only face normals would report a false collision here and the beams would bump into each other in mid-air.

Test yourself

How many candidate axes does SAT test for two oriented boxes in 2D?

  1. 2
  2. 4
  3. 8
  4. 15

Which axis becomes the contact normal when the boxes overlap?

  1. The first axis tested
  2. The axis with the largest overlap
  3. The axis with the smallest overlap, flipped to point from A to B
  4. Always the world up axis

Why does 3D OBB-OBB SAT include the 9 cross products of edge directions?

  1. To compute contact points
  2. Two boxes can be separated by a plane that is parallel to one edge of each box, which no face normal finds
  3. To normalize the face axes
  4. They are only needed for spheres