Box2D v3 and Rapier
Not every game uses a big engine. Custom engines, web games, servers that simulate the authoritative world, and tools often embed a physics library directly. Two of the most popular open-source ones:
- Box2D: the classic 2D rigid-body library by Erin Catto, written in C. Version 3 is a rewrite with a new solver, multithreading and a C API built on IDs instead of pointers. Engines from Unity's 2D physics to many indie frameworks have been built on Box2D over the years.
- Rapier: a 2D and 3D physics library written in Rust by Dimforge, with official JavaScript/TypeScript bindings compiled to WebAssembly. It is a common choice for web games and Rust engines such as Bevy.
Both are under permissive open-source licences (check current terms). The code below is real library code that can't run on the site; the C++ block models one of Box2D v3's main ideas.
Box2D v3: hello world
Box2D v3.2.0 is the current release (October 2026). Everything is created from a definition struct with defaults and referenced by a small ID value:
#include "box2d/box2d.h"
#include <stdio.h>
int main(void)
{
b2WorldDef worldDef = b2DefaultWorldDef();
worldDef.gravity = (b2Vec2){0.0f, -10.0f};
b2WorldId worldId = b2CreateWorld(&worldDef);
b2BodyDef groundDef = b2DefaultBodyDef(); // static by default
groundDef.position = (b2Pos){0.0f, -10.0f};
b2BodyId groundId = b2CreateBody(worldId, &groundDef);
b2Polygon groundBox = b2MakeBox(50.0f, 10.0f); // half-widths, in meters
b2ShapeDef groundShape = b2DefaultShapeDef();
b2CreatePolygonShape(groundId, &groundShape, &groundBox);
b2BodyDef bodyDef = b2DefaultBodyDef();
bodyDef.type = b2_dynamicBody;
bodyDef.position = (b2Pos){0.0f, 4.0f};
b2BodyId bodyId = b2CreateBody(worldId, &bodyDef);
b2Polygon box = b2MakeBox(1.0f, 1.0f);
b2ShapeDef shapeDef = b2DefaultShapeDef();
shapeDef.density = 1.0f;
shapeDef.material.friction = 0.3f;
b2CreatePolygonShape(bodyId, &shapeDef, &box);
const float timeStep = 1.0f / 60.0f;
const int subStepCount = 4;
for (int i = 0; i < 90; ++i)
{
b2World_Step(worldId, timeStep, subStepCount);
b2Pos p = b2Body_GetPosition(bodyId);
b2Rot r = b2Body_GetRotation(bodyId);
printf("%4.2f %4.2f %4.2f\n", p.x, p.y, b2Rot_GetAngle(r));
}
b2DestroyWorld(worldId);
return 0;
}Note: In v3.2, world positions are
b2Pos, which is simplyb2Vec2unless you build Box2D with double precision for very large worlds. Code for v3.0 and v3.1 usesb2Vec2there. Friction and restitution moved intoshapeDef.materialin v3.1; v2.4 tutorials (b2World world(gravity),body->CreateFixture) are a different, C++ API.
Things the hello world teaches:
- Units are meters, kilograms, seconds. Box2D is tuned for moving objects between about 0.1 and 10 m. Convert pixels at the boundary (for example 1 m = 32 px); a 400-"meter" crate falls in slow motion and stacks badly.
- IDs, not pointers.
b2BodyIdis a small struct; a stale ID is detectable (b2Body_IsValid) instead of being a dangling pointer. - Events are read after the step, in bulk:
b2World_GetContactEvents(worldId)returns arrays of begin, end and hit events (enable them per shape in the shape def), and sensors report throughb2World_GetSensorEvents. There are no callbacks firing in the middle of the solver, where it is unsafe to delete bodies. - Continuous collision is on for dynamic bodies against static ones; mark fast dynamic bodies that must not pass through other dynamic bodies with
bodyDef.isBullet = true.
Sub-stepping instead of iterations
The last argument of b2World_Step is the sub-step count. Box2D v3's "soft step" solver splits each step into sub-steps and does one relaxed solve per sub-step, instead of the classic approach of many solver iterations per step. For the same amount of work, sub-steps win: each one moves positions a little and then fixes the constraints from a fresh, nearly correct state.
Here is the effect on a chain of 10 light links with a heavy weight on the end, released from horizontal (position-based distance constraints, as in Distance Constraints), one second at 60 Hz, with the same number of constraint solves per frame:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
#include <algorithm>
struct P { double x, y, px, py; };
double chainStretch(int substeps, int iterations) {
const int n = 11; // 11 points, 10 links of 0.1 m
const double rest = 0.1, g = -9.8, frameDt = 1.0 / 60;
// the pin never moves; the last point is a 20 kg weight on 1 kg links
auto invMass = [&](int i) { return i == 0 ? 0.0 : (i == n - 1 ? 1.0 / 20 : 1.0); };
std::vector<P> p(n);
for (int i = 0; i < n; i++) p[i] = {i * rest, 0, i * rest, 0}; // starts horizontal, pinned at x = 0
const double h = frameDt / substeps;
double worst = 0;
for (int frame = 0; frame < 60; frame++) {
for (int s = 0; s < substeps; s++) {
for (int i = 1; i < n; i++) { // Verlet-style predict
double vx = p[i].x - p[i].px, vy = p[i].y - p[i].py;
p[i].px = p[i].x; p[i].py = p[i].y;
p[i].x += vx; p[i].y += vy + g * h * h;
}
for (int it = 0; it < iterations; it++)
for (int i = 0; i + 1 < n; i++) {
double dx = p[i + 1].x - p[i].x, dy = p[i + 1].y - p[i].y;
double len = std::sqrt(dx * dx + dy * dy), diff = (len - rest) / len;
double wa = invMass(i), wb = invMass(i + 1), sum = wa + wb;
p[i].x += dx * diff * wa / sum; p[i].y += dy * diff * wa / sum;
p[i + 1].x -= dx * diff * wb / sum; p[i + 1].y -= dy * diff * wb / sum;
}
}
double total = 0; // measured once per frame
for (int i = 0; i + 1 < n; i++) total += std::hypot(p[i + 1].x - p[i].x, p[i + 1].y - p[i].y);
worst = std::max(worst, total / (rest * (n - 1)));
}
return worst;
}
int main() {
std::cout << std::fixed << std::setprecision(3);
std::cout << "1 step, 8 iterations: worst length " << chainStretch(1, 8) << " x rest\n";
std::cout << "2 steps, 4 iterations: worst length " << chainStretch(2, 4) << " x rest\n";
std::cout << "4 steps, 2 iterations: worst length " << chainStretch(4, 2) << " x rest\n";
std::cout << "8 steps, 1 iteration: worst length " << chainStretch(8, 1) << " x rest\n";
}1 step, 8 iterations: worst length 1.215 x rest
2 steps, 4 iterations: worst length 1.116 x rest
4 steps, 2 iterations: worst length 1.065 x rest
8 steps, 1 iteration: worst length 1.037 x rest
Every row does eight constraint passes per frame, yet the more the work is spread over sub-steps, the closer the chain stays to its true length: the worst stretch drops from 21.5% to 3.7%. That is why the Box2D v3 documentation steps with 4 sub-steps rather than asking you to raise iteration counts, and why XPBD-style solvers took the same route.
Rapier in JavaScript
Rapier publishes several npm packages: @dimforge/rapier2d and @dimforge/rapier3d, the -compat variants that embed the WebAssembly in the JS file (easiest with any bundler), -simd builds, and -deterministic builds that give bit-identical results across platforms (for lockstep multiplayer and replays).
import RAPIER from '@dimforge/rapier2d-compat';
await RAPIER.init(); // loads the WebAssembly module
const world = new RAPIER.World({ x: 0.0, y: -9.81 }); // world.timestep defaults to 1/60
world.createCollider(RAPIER.ColliderDesc.cuboid(10.0, 0.1)); // no parent body: fixed ground
const ball = world.createRigidBody(
RAPIER.RigidBodyDesc.dynamic().setTranslation(0.0, 4.0).setCcdEnabled(true));
world.createCollider(RAPIER.ColliderDesc.ball(0.5).setRestitution(0.4).setFriction(0.7), ball);
for (let i = 0; i < 60; i++) world.step(); // one call per fixed tick
const p = ball.translation();
console.log(p.x.toFixed(2), p.y.toFixed(2));Rapier also ships a kinematic character controller, the collide-and-slide controller of this course with slopes, steps and snapping as options:
const controller = world.createCharacterController(0.01); // skin offset
controller.enableAutostep(0.3, 0.2, true); // max step height, min step width, step onto dynamic bodies
controller.enableSnapToGround(0.3);
controller.setMaxSlopeClimbAngle(45 * Math.PI / 180);
function tick(desired) { // desired = { x, y } movement this tick
controller.computeColliderMovement(playerCollider, desired);
const move = controller.computedMovement();
const p = playerBody.translation(); // a kinematicPositionBased body
playerBody.setNextKinematicTranslation({ x: p.x + move.x, y: p.y + move.y });
grounded = controller.computedGrounded();
}Two more features worth knowing: world.takeSnapshot() / RAPIER.World.restoreSnapshot(bytes) serialize the entire world (save games, rollback netcode), and world.numSolverIterations trades accuracy for speed.
Choosing
| Box2D v3 | Rapier | |
|---|---|---|
| dimensions | 2D | 2D and 3D |
| language | C (any language with C FFI) | Rust; JS/TS via WebAssembly |
| determinism | deterministic by design, with cross-platform determinism a stated goal of v3 (test on your targets) | enhanced-determinism feature (Rust) / -deterministic npm builds |
| character controller | build your own on the capsule "mover" helpers (b2World_CastMover, b2World_CollideMover) |
built in |
| best for | 2D games in C/C++, custom engines | web games, Rust/Bevy, 3D without a big engine |
Test yourself
In Box2D v3, what does the last argument of b2World_Step(worldId, timeStep, subStepCount) control?
- How many frames to skip
- How many sub-steps the soft-step solver splits the step into
- The number of threads
- The number of bodies
Your Box2D game uses pixels as units and a 64-unit crate. What is likely wrong?
- Nothing
- Box2D is tuned for meter-sized objects, so 64-meter crates fall slowly and behave badly; convert pixels to meters
- Box2D only accepts integers
- Crates must be circles
With the same total number of constraint passes per frame, why do sub-steps keep a chain closer to its rest length than extra iterations?
- They use doubles
- Each sub-step solves from a fresh, nearly correct state with a smaller dt, so errors don't build up
- Iterations are skipped by the compiler
- They don't; both are identical