Building a 2D rigid-body physics engine in Rust

Basic rigid-body math looks easy on paper: add gravity to velocity, add velocity to position, push overlapping shapes apart. Then you stack a pyramid of 105 boxes or fire a fast circle at a thin wall. Without proper constraint solving and swept collision checks, the stack jitters itself apart in three seconds and the bullet passes straight through the wall between frames.

I wrote Ro-Physics in Rust, along with a live WGPU testbed, to work through each of those failure cases myself.

let mut world = World::with_gravity(Vec2::new(0.0, -9.81));
let ground = world.create_static_body(Transform::identity());
world.add_box(ground, Vec2::new(10.0, 0.5), 0.0);

What it took to keep a 105-box stack still

Collision detection uses the Separating Axis Theorem (SAT) for convex polygons and direct analytical checks for circles, producing contact manifolds with penetration depth and surface normals.

To resolve contacts without launching bodies into orbit, a sequential impulse solver iterates velocity and position constraints across contact points as well as distance, revolute, and motor joints. Coulomb friction keeps stacked boxes from sliding like ice, and bodies whose kinetic energy stays below a threshold for several frames go to sleep until another body wakes them.

High-speed tunneling needed a separate pass: continuous collision detection (CCD) sweeps fast-moving bodies across the fixed timestep to find their earliest time of impact before discrete overlap misses a thin barrier. Above all of that, a bounding volume hierarchy (BVH) filters broadphase pairs and handles interactive mouse picks, AABB checks, and raycasts in the viewer.

Running the whole world on a fixed timestep also means the same initial scene steps identically from run to run, which made debugging corner cases much like running perft in my Rust Chess Engine.


Linked mentions

You might also enjoy