Skip to content
Velloreth
Gaming 11 min read

Game Physics Engines: How They Work

Inside a rigid body physics engine: broad phase, narrow phase, integration, sequential impulse solving, position correction, fixed timesteps, and tuning.

By

A physics engine does not simulate physics. It runs an approximation pipeline that produces motion which reads as physical, given a fixed budget of milliseconds per frame.

Understanding that pipeline is what separates “the box falls over and it looks right” from being able to diagnose why the stack jitters, why the character falls through the floor at 40 fps, or why adding a hundred crates turns 8 ms into 60 ms.

The frame, end to end

apply forces/torques
        │
        ▼
   broad phase  ──►  candidate pairs (AABB overlap)
        │
        ▼
   narrow phase ──►  contact manifolds (points, normals, depths)
        │
        ▼
   integrate velocities   v += (F/m)·dt
        │
        ▼
   solve velocity constraints (iterative impulses, warm started)
        │
        ▼
   integrate positions    x += v·dt
        │
        ▼
   correct positions      (split impulse / nonlinear Gauss-Seidel)
        │
        ▼
   narrow/sleep culling, island sleeping

Two things to internalize. First, detection and response are separate: the narrow phase produces geometry (a normal and one or more points with penetration depth), and the solver turns that geometry into motion. Second, the engine never works with contact forces — it works with impulses, which are forces integrated over the timestep. Impulses change velocity directly, which is both cheaper and numerically better behaved.

Broad phase: cheap rejection before expensive math

The narrow phase between two complex shapes is expensive. The broad phase’s only job is to avoid running it for the thousands of pairs that cannot possibly be touching.

AlgorithmCostBehaviour
Brute forceO(n²)Fine below ~50 bodies, unusable past that
Sort and sweep (SAP)O(n log n + k)Excellent for mostly-static scenes; degrades when many objects move
Spatial hash / uniform gridO(n) amortizedGreat for uniform sizes (platformer debris); bad with wildly different scales
Dynamic AABB treeO(log n)Good general choice, used by Box2D and Bullet
BVHO(log n)Best for large static geometry; build cost amortized

The output is a pair list, filtered by broad-phase filters — collision layers and masks that say “player collides with world and enemies, but not with other players’ bullets.” Doing that here rather than in the narrow phase is the single cheapest optimisation in most engines.

The important property of the result is that it must be stable: the same pair should keep the same contact IDs across frames so the solver can reuse previous impulses. Box2D derives contact identifiers from the clipped feature indices (which edge met which face), which is exactly what makes warm starting possible.

Narrow phase: from overlap to manifold

The narrow phase answers “how much do these two shapes overlap, and along which direction.”

SAT (Separating Axis Theorem) is the workhorse for polygons and boxes: project both shapes onto each candidate axis (edge normals plus, for polygons, face normals), and if any axis shows a gap, they are not touching. The axis with the least penetration is your contact normal. It is simple, robust, and has no trouble producing a normal — but the naive version gives you one point, and a single point cannot stop a box from rotating as it settles.

Clipping fixes that. Once SAT identifies the reference face and the incident face on the other shape, you clip the incident face against the reference face’s side planes and keep the points that lie inside the other shape. You end up with two points for a face-on-face box contact (a manifold), which is what gives stacking its stability.

GJK + EPA is the alternative: Gilbert–Johnson–Keerthi finds whether the shapes intersect using only distance queries on support points, and the Expanding Polytope Algorithm recovers the penetration vector when they do. It is the better choice for smooth and mixed shape types — circles, capsules, spheres, convex hulls — where enumerating axes is awkward. Most engines use SAT for polygon–polygon and GJK/EPA for the rest.

The output, the contact manifold, is a small set of points, each carrying: position, normal, penetration depth, and a stable ID. Everything downstream reads this and nothing else.

Integration: why semi-implicit Euler

The naive approach is explicit (forward) Euler:

v += a·dt
x += v·dt        ← uses the updated v, making this semi-implicit

Explicit Euler uses the old velocity for position, which pumps energy into oscillating systems — a spring will spiral outward. Semi-implicit Euler updates velocity first and uses the new velocity for position. It is the same amount of arithmetic, unconditionally more stable for the systems games contain, and it is what essentially every game engine ships with.

Runge–Kutta (RK4) is more accurate and is worth it for orbital or projectile prediction where you integrate only a few bodies. For hundreds of constrained rigid bodies, the extra accuracy costs four evaluations per step and buys you little, because the contact solver’s error dominates anyway.

Higher-order integration also does not fix a variable timestep. Nothing does.

The solver: sequential impulses

A contact constraint says: these two surfaces may not approach each other along the normal, and may not slide along the tangent beyond friction.

Written properly, solving all constraints simultaneously requires a large linear system — accurate, but far too expensive per frame. Games use an approximation: solve each constraint individually, repeat, and let the errors shrink.

Erin Catto’s GDC talks on sequential impulses lay out the loop:

for iter in 0..velocityIterations:
    for contact in contacts:
        compute relative velocity at the point
        compute impulse that would zero the approach velocity
        clamp normal impulse to be >= 0        (never pull together)
        clamp change against accumulated impulse (friction cone)
        apply impulse to both bodies

This is Gauss-Seidel iteration applied to the constraint system. It converges toward a valid solution but never quite arrives — and that is acceptable, because the next frame starts again from a good place.

Three details decide whether stacking works:

Warm starting. Take last frame’s impulse for this contact ID and apply it before iterating. The solver starts near the answer instead of at zero, and convergence in 8 iterations with warm starting beats convergence in 80 without. This is the single most important implementation detail in an impulse solver.

Accumulated impulse clamping. You must remember the total impulse applied so far and only ever allow it to grow for a non-negative constraint. Without this, the solver applies contradictory impulses on successive iterations and the stack vibrates.

Tangent clamping for friction. Coulomb friction says the tangential impulse magnitude is bounded by μ · normalImpulse. Friction without reference to the normal force is a source of objects that slide when they should grip, or grip impossibly.

Iteration count is your primary quality knob. Box2D defaults have historically sat around 8 velocity iterations; stacks of many bodies want more. Cost scales linearly with iterations times contacts, which is why a scene with 500 touching crates costs dramatically more than 500 isolated ones.

Position correction: Baumgarte versus split impulses

Velocity solving leaves penetration: you stopped the surfaces approaching, but they are still 3 mm inside each other. Something has to push them apart.

Baumgarte stabilization folds a fraction of the positional error back into the velocity constraint. It is one line and cheap, but it injects energy — the stack visibly bounces, and at high correction factors it explodes.

Split impulse (a.k.a. nonlinear Gauss-Seidel position correction) runs a second, separate solver pass that applies positional impulses that do not change linear velocity permanently. Objects separate without gaining momentum. This is what modern engines default to, and it is why you do not see the classic Baumgarte bounce.

Either way you need slop: allow a small penetration (Box2D uses 5 mm at its default scale) before any correction kicks in. Otherwise the solver fights sub-millimetre floating point noise every frame, and the fight is what you see as jitter.

A practical configuration:

ParameterStarting valueRaise it when
Velocity iterations8Stacks shiver, joints feel springy
Position iterations3Objects visibly sink into each other
Linear slop0.005 mResting contacts buzz
Baumgarte/split factor0.2Separation is too slow
Restitution threshold1 m/sSmall drops keep bouncing forever

That last row matters: restitution should only apply above a threshold velocity, or a ball resting on the floor will bounce microscopically for all eternity because every frame registers a “collision.”

Fixed timestep, accumulation, and tunnelling

Pass your render delta to step() and you get three problems: physics that changes behaviour at low frame rate, non-reproducible simulations, and a solver whose convergence varies with frame timing.

The standard pattern:

const float dt = 1.0f / 60.0f;
float accumulator = 0.0f;

void frame(float frameTime) {
    accumulator += frameTime;
    while (accumulator >= dt) {
        world.step(dt, velocityIterations, positionIterations);
        accumulator -= dt;
    }
    float alpha = accumulator / dt;      // 0..1
    render(interpolate(previousState, currentState, alpha));
}

The simulation always advances in identical 16.67 ms steps; rendering interpolates between the last two states so a 144 Hz display does not look choppy. Clamp frameTime (to, say, 0.25 s) before accumulating, or a breakpoint in the debugger will trigger a thousand-step catch-up spiral the moment you resume.

Substeps are the other quality axis. Box2D 3.x takes a sub-step count alongside the primary timestep, and its own docs note that a 60 Hz step with 8 sub-steps is effectively solving at 480 Hz. Substeps improve accuracy for fast or tightly-constrained systems (a scissor lift, a chain of joints) without changing your game’s logical tick.

Tunnelling is the discrete-detection failure: a fast object moves from in front of a thin wall to behind it in one step, and the end-of-step position check finds nothing. Fixes, in order of preference:

  • CCD / swept tests. Sweep the shape from old to new transform and compute the time of impact; Box2D does this by default for dynamic bodies against static ones.
  • Sphere/capsule casting for characters, which is cheaper than full shape sweeping.
  • Speculative contacts — generate contacts with a margin proportional to velocity so the constraint exists before the shapes overlap.
  • Raycasts against fast-moving geometry in your own movement code, for character controllers where you want deterministic, tunable behaviour.

Determinism, and why it is harder than it sounds

If your game replays, locks steps across peers, or saves a seed and expects the same world, you need bit-identical results. Floating point makes that fragile: different compilers, optimisation levels, x87 vs SSE, FMA contraction, or simply a different body creation order can change the last bits — and a chaotic simulation amplifies them.

Practical rules:

  • Fix the body/shape creation order; many engines use creation order to order the solver.
  • Avoid pow, exp, and library math that may be implemented differently per platform; prefer operations you control.
  • Do not let the accumulation order depend on hash-map iteration or thread scheduling. Box2D 3.x bases simulation order on creation order specifically to keep multithreaded runs deterministic, and it runs a determinism test on every pull request.
  • Never let the physics step depend on wall-clock time or render order.

Cross-platform float determinism is genuinely hard — historically Box2D has said it does not guarantee it across binaries. If you need that guarantee, budget for fixed-point math or a lockstep design that keeps all peers on the same binary.

Reading the symptoms

SymptomMost likely cause
Stack shivers at restCold solver (no warm starting), too few iterations, no slop
Objects sink and stayNo position solver, or position iterations too low
Objects pop apart violentlyBaumgarte correction too aggressive; use split impulse
Ball bounces forever on floorNo restitution threshold
Behaviour changes at 30 fpsVariable timestep
Tunneling through thin wallsMissing CCD or swept character movement
Jitter only in one sceneA kinematic body being pushed by a static one, or a very large/small world scale
Simulation explodes after adding bodiesMass ratio too extreme, or a joint fighting a contact

The last one is worth calling out: ratios beyond roughly 1:10 between connected bodies cause solver convergence to fall apart. Do not simulate an ant pushing a boulder with real masses.

Choosing an engine

For 2D, Box2D is the default for good reasons — MIT licensed, small, well documented, and its GDC material is still the best explanation of impulse solving available. Chipmunk2D is a fine alternative with a different API. For 3D, Bullet and Jolt are the two credible open options; Jolt has gained a reputation for stability in large piles and ships with good examples, and both have been used in shipped titles.

Before integrating anything, run its own testbed and look at the failure cases: a pyramid stack, a chain of 50 links, a fast bullet against a thin wall, and a scene with mixed mass ratios. What a library does at those four points tells you more than its feature list.

The place to start is not the tuning table but the pipeline diagram. When something looks wrong, ask which stage produced it — the pair list, the manifold, the solver, the correction, or the integrator — and you will usually have the cause before you open a profiler.

Frequently asked questions

What does a physics engine actually compute each frame?
It finds potentially overlapping pairs with a broad phase, reduces real overlaps to contact manifolds in the narrow phase, then iteratively solves velocity constraints at those contact points using impulses, and finally integrates positions. Position correction and sleeping run after that.
Why do my objects jitter when stacked?
Almost always a cold solver or position error fighting velocity resolution. Raise the velocity and position iteration counts, enable warm starting so the solver does not restart from zero each frame, and add penetration slop so contacts are not forced to exactly zero depth.
What timestep should I use?
A fixed 1/60 s (60 Hz) with an accumulator is the standard choice; Box2D's documentation notes 1/30 s or smaller works and 1/60 usually delivers high quality. Never pass your variable render delta to the solver — physics becomes non-deterministic and frame-rate dependent.
Why do fast objects pass through walls?
Discrete collision detection only checks positions at the end of a step, so an object can move from one side of a thin surface to the other between checks. Continuous collision detection sweeps the shape from its old to new position and computes the time of impact; use it for fast or thin geometry.