The Collision Pipeline
Every physics step has to answer one question for the whole world: which pairs of shapes touch, and how? Asking it naively means testing every shape against every other shape. With n bodies that is n(n-1)/2 pair tests: 4,950 for 100 bodies and almost 500,000 for 1,000. Most of those pairs are on opposite sides of the level and can't possibly touch. Engines therefore split collision handling into stages, each one cheaper than the next and each one throwing away most of what it receives.
The four stages
| Stage | Question | Typical cost per test | Output |
|---|---|---|---|
| Filtering | Are these two kinds of object allowed to collide at all? | one bitwise AND | allowed pairs |
| Broad phase | Do their bounding boxes overlap? | a few comparisons | candidate pairs |
| Narrow phase | Do the actual shapes overlap, and where? | tens to hundreds of operations | contacts (normal, depth, points) |
| Response | How should velocities and positions change? | a solver iteration | new velocities |
The broad phase works on AABBs (axis-aligned bounding boxes, see AABB) because comparing two boxes takes four comparisons, whatever shape is inside them. The next three lessons cover three broad-phase structures: the uniform grid, sweep and prune and the BVH. The narrow phase then runs exact tests such as SAT and GJK on the survivors, and the response section turns contacts into impulses.
Collision shapes
Physics engines don't collide your render meshes. Each body carries one or more simple collision shapes, chosen for speed:
| Shape | Good for | Notes |
|---|---|---|
| Sphere / circle | balls, projectiles, rough proxies | cheapest test of all: compare a distance with the sum of radii |
| Capsule | characters, limbs | a segment with a radius; slides smoothly over steps and edges |
| Box | crates, walls, vehicles | the OBB test needs SAT |
| Convex hull | rocks, props | GJK/EPA or SAT; keep the vertex count low (engines cap it) |
| Triangle mesh | static level geometry | usually allowed only on static bodies |
| Compound | anything else | several convex pieces on one body |
Note: A dynamic body made of a concave triangle mesh is either unsupported or very slow in most engines. Split concave shapes into convex pieces, or approximate them with a few boxes and capsules.
Layers and masks
Filtering comes first because it is the cheapest. Each collider belongs to one or more layers (bits in an integer) and has a mask saying which layers it wants to collide with. Two colliders interact if each one's mask contains the other's layer:
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdint>
enum Layer : uint32_t {
Player = 1u << 0, Enemy = 1u << 1, PlayerShot = 1u << 2, EnemyShot = 1u << 3, World = 1u << 4,
};
struct Collider { std::string name; uint32_t layer; uint32_t mask; };
bool canCollide(const Collider& a, const Collider& b) {
return (a.layer & b.mask) != 0 && (b.layer & a.mask) != 0; // both must agree
}
int main() {
Collider all[] = {
{"player", Player, Enemy | EnemyShot | World},
{"enemy", Enemy, Player | PlayerShot | World},
{"playerShot", PlayerShot, Enemy | World},
{"enemyShot", EnemyShot, Player | World},
{"wall", World, Player | Enemy | PlayerShot | EnemyShot},
};
std::cout << std::setw(11) << "";
for (const auto& c : all) std::cout << std::setw(11) << c.name;
std::cout << "\n";
for (const auto& a : all) {
std::cout << std::setw(11) << a.name;
for (const auto& b : all) std::cout << std::setw(11) << (canCollide(a, b) ? "x" : ".");
std::cout << "\n";
}
} player enemy playerShot enemyShot wall
player . x . x x
enemy x . x . x
playerShot . x . . x
enemyShot x . . . x
wall x x x x .
The table is symmetric because the rule checks both directions. Player shots pass through the player and through each other, enemy shots ignore enemies, and walls stop everything except other walls (static geometry never needs to test against static geometry anyway).
Engines expose the same idea with different names:
| Engine | Where you set it |
|---|---|
| Unity | a layer per GameObject; the Layer Collision Matrix in Project Settings > Physics; LayerMask for queries |
| Unreal | an object channel per component, and per-channel responses (Block, Overlap, Ignore) in collision presets |
| Godot | collision_layer (what I am) and collision_mask (what I look for) on every physics body and area |
| Box2D v3 | filter.categoryBits and filter.maskBits on a shape definition |
Tip: Name your layers once, in one place (an enum, a constants file, the project settings), and never use magic numbers like
1 << 7in gameplay code. A layer that silently changes meaning breaks collisions in levels nobody is testing.
Counting the work
The point of the pipeline is to cut the number of expensive tests. This program places 200 circles in a 100 × 100 world (scattered with a seeded generator) and counts how much work each stage does:
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <cstdint>
struct Lcg { // a tiny seeded generator: same numbers on every run
uint32_t s;
void seed(uint32_t v) { s = v; }
double next() { s = s * 1664525u + 1013904223u; return (s >> 8) / 16777216.0; } // 0..1
};
struct Circle { double x, y, r; uint32_t layer, mask; };
int main() {
Lcg g; g.seed(42);
std::vector<Circle> cs;
for (int i = 0; i < 200; i++) {
uint32_t layer = (i % 4 == 0) ? 1u : 2u; // a quarter are "players", the rest "debris"
uint32_t mask = (layer == 1u) ? 3u : 1u; // debris ignores other debris
cs.push_back({g.next() * 100, g.next() * 100, 1 + g.next() * 2, layer, mask});
}
long pairs = 0, filtered = 0, boxHits = 0, exactHits = 0;
for (size_t i = 0; i < cs.size(); i++)
for (size_t j = i + 1; j < cs.size(); j++) {
pairs++;
const Circle &a = cs[i], &b = cs[j];
if (!((a.layer & b.mask) && (b.layer & a.mask))) continue;
filtered++;
double r = a.r + b.r; // AABB test first
if (std::fabs(a.x - b.x) > r || std::fabs(a.y - b.y) > r) continue;
boxHits++;
double dx = a.x - b.x, dy = a.y - b.y; // then the exact test
if (dx * dx + dy * dy <= r * r) exactHits++;
}
std::cout << "all pairs: " << pairs << "\n";
std::cout << "after layer filter: " << filtered << "\n";
std::cout << "AABBs overlap: " << boxHits << "\n";
std::cout << "circles really touch: " << exactHits << "\n";
}all pairs: 19900
after layer filter: 8725
AABBs overlap: 43
circles really touch: 34
Even this brute-force loop shows the funnel: the layer filter removes more than half the pairs with one AND each, and the AABB test leaves only a handful for the exact test. What it doesn't fix is the first line: we still visited every pair. That n² loop is what the broad-phase structures in the next lessons remove.
Test yourself
Why does the broad phase test bounding boxes rather than the real shapes?
- Bounding boxes are more accurate
- A box test costs a few comparisons whatever the shape, and most pairs fail it
- The narrow phase can't handle boxes
- Engines can only store boxes
Collider A has layer Enemy and a mask that includes PlayerShot. Collider B is a PlayerShot whose mask does not include Enemy. With the two-way rule, do they collide?
- Yes, because A wants to hit B
- No, both masks must accept the other's layer
- Only in the broad phase
- It depends on their speed
How many pair tests does a brute-force check of 1,000 bodies perform?
- 1,000
- about 10,000
- 499,500
- 1,000,000