TExcelTAD
Home › 3D Web Games with Three.js › Physics with Rapier

Physics with Rapier

Rapier is a physics engine written in Rust by Dimforge and compiled to WebAssembly for the web. It is much faster than pure-JavaScript engines, deterministic across machines (with the same build and inputs), actively developed, and comes with features games need out of the box: a kinematic character controller, sensors, collision groups, joints, continuous collision detection (CCD), ray and shape casts, and a debug renderer. It's the default choice for new Three.js games that need real physics; react-three-fiber's @react-three/rapier wraps the same engine.

Loading

The @dimforge/rapier3d-compat package embeds its WASM binary in the JavaScript file, so it works with any bundler and in this course's playgrounds. It must be initialised once before use:

js
import RAPIER from '@dimforge/rapier3d-compat';
await RAPIER.init();                                      // loads the WebAssembly module
const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 });

(The non-compat @dimforge/rapier3d package loads a separate .wasm file and needs bundler support for WASM imports.)

Bodies and colliders

Rapier separates rigid bodies (mass, velocity, type) from colliders (shape, friction, restitution, density). Both are created from descriptions, and a collider is attached to a body when created. A collider without a body is fixed in the world, ideal for level geometry.

Body description Moves by Use
RigidBodyDesc.dynamic() forces, gravity, collisions crates, balls, debris, ragdolls
RigidBodyDesc.fixed() never moves floors, walls (or just a collider with no body)
RigidBodyDesc.kinematicPositionBased() you set the next position (setNextKinematicTranslation) moving platforms, doors, characters
RigidBodyDesc.kinematicVelocityBased() you set the velocity conveyor-like movers
Collider description Shape Note
ColliderDesc.ball(r) sphere
ColliderDesc.cuboid(hx, hy, hz) box half extents, like cannon-es
ColliderDesc.capsule(halfHeight, r) capsule along Y halfHeight is the straight part only; characters
ColliderDesc.cylinder(halfHeight, r), cone(…)
ColliderDesc.convexHull(points) convex hull of a point cloud dynamic props from meshes
ColliderDesc.trimesh(vertices, indices) triangle mesh static level geometry
ColliderDesc.heightfield(…) grid of heights terrain

Chain setters on descriptions: .setTranslation(x, y, z), .setRotation({ x, y, z, w }), .setRestitution(0.5), .setFriction(0.8), .setDensity(2) (mass comes from density × volume unless you set it).

Deterministic stepping

world.step() advances one step of world.timestep (1/60 s by default). This prints a ball's bounce and a box sliding to a stop on a ramp-free floor after a push (output under the frame):

html · try it yourself
<script type="module">
import RAPIER from '@dimforge/rapier3d-compat';
await RAPIER.init();

const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 });
console.log(`timestep ${world.timestep.toFixed(4)} s`);
world.createCollider(RAPIER.ColliderDesc.cuboid(20, 0.1, 20).setTranslation(0, -0.1, 0).setFriction(0.5));

const ball = world.createRigidBody(RAPIER.RigidBodyDesc.dynamic().setTranslation(-2, 3, 0));
world.createCollider(RAPIER.ColliderDesc.ball(0.5).setRestitution(0.7), ball);

const box = world.createRigidBody(RAPIER.RigidBodyDesc.dynamic().setTranslation(2, 0.5, 0));
world.createCollider(RAPIER.ColliderDesc.cuboid(0.5, 0.5, 0.5).setFriction(0.5), box);
box.applyImpulse({ x: 4, y: 0, z: 0 }, true);       // mass 1 (density 1 x 1 m³): 4 m/s to the right

for (let i = 1; i <= 90; i++) {
  world.step();
  if (i % 15 === 0) {
    const b = ball.translation(), x = box.translation(), v = box.linvel();
    console.log(`t=${(i / 60).toFixed(2)}s  ball y=${b.y.toFixed(2)}  box x=${x.x.toFixed(2)} vx=${v.x.toFixed(2)}`);
  }
}
</script>

Expected console output:

text
timestep 0.0167 s
t=0.25s  ball y=2.69  box x=2.84 vx=2.77
t=0.50s  ball y=1.76  box x=3.38 vx=1.55
t=0.75s  ball y=0.51  box x=3.61 vx=0.32
t=1.00s  ball y=0.78  box x=3.62 vx=0.00
t=1.25s  ball y=0.51  box x=3.62 vx=0.00
t=1.50s  ball y=0.50  box x=3.62 vx=0.00

The ball bounces much less than its restitution of 0.7 suggests: Rapier combines the coefficients of the two touching colliders, by default with the average, and the floor's restitution is 0. Set .setRestitution() on both, or change the rule with setRestitutionCombineRule(RAPIER.CoefficientCombineRule.Max). Friction is combined the same way, which is why the pushed box slides 1.6 m and stops.

Two habits to note: translation(), rotation() and linvel() return new plain objects each call ({ x, y, z } / { x, y, z, w }), and Rapier's methods that can wake a sleeping body take a wakeUp boolean (applyImpulse(impulse, true)).

Rapier with Three.js

Sync meshes the same way as with cannon-es, reading the body each frame:

js
const p = body.translation(), q = body.rotation();
mesh.position.set(p.x, p.y, p.z);
mesh.quaternion.set(q.x, q.y, q.z, q.w);

The playground builds a spiral of dominoes. Click to tip the first one; D toggles Rapier's debug renderer, which draws every collider as lines. The debug view is the first thing to turn on when physics misbehaves: it shows where the colliders really are, which is often not where the meshes are.

html · try it yourself
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }
#hud { position: fixed; left: 10px; top: 8px; color: #fff; font: 13px system-ui, sans-serif; text-shadow: 0 1px 2px #000; pointer-events: none }</style>
<div id="hud">Click to push the first domino, D toggles debug lines, R resets</div>
<script type="module">
import * as THREE from 'three';
import RAPIER from '@dimforge/rapier3d-compat';
await RAPIER.init();

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#1d2433');
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 9, 12);
camera.lookAt(0, 0, 0);
addEventListener('resize', () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});
scene.add(new THREE.HemisphereLight('#fff', '#334', 1.4));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(4, 10, 6);
scene.add(sun);
const floor = new THREE.Mesh(new THREE.PlaneGeometry(30, 30), new THREE.MeshStandardMaterial({ color: '#3b4a5e' }));
floor.rotation.x = -Math.PI / 2;
scene.add(floor);

let world, pairs = [];
const dominoGeo = new THREE.BoxGeometry(0.2, 1, 0.5);
function build() {
  for (const { mesh } of pairs) scene.remove(mesh);
  pairs = [];
  world?.free();                                    // release the old world's WASM memory
  world = new RAPIER.World({ x: 0, y: -9.81, z: 0 });
  world.createCollider(RAPIER.ColliderDesc.cuboid(15, 0.1, 15).setTranslation(0, -0.1, 0));
  let a = 0;
  for (let i = 0; i < 48; i++) {
    const r = 1.5 + a * 0.35;                          // an outward spiral...
    a += 0.55 / r;                                     // ...with dominoes 0.55 m apart along it
    const x = Math.cos(a) * r, z = Math.sin(a) * r;
    // Turn the thin side (local x) along the spiral's direction of travel (-sin a, 0, cos a).
    const q = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), -a - Math.PI / 2);
    const body = world.createRigidBody(RAPIER.RigidBodyDesc.dynamic().setTranslation(x, 0.5, z).setRotation(q));
    world.createCollider(RAPIER.ColliderDesc.cuboid(0.1, 0.5, 0.25).setFriction(0.6), body);
    const mesh = new THREE.Mesh(dominoGeo, new THREE.MeshStandardMaterial({ color: new THREE.Color().setHSL(i / 48, 0.65, 0.55) }));
    scene.add(mesh);
    pairs.push({ mesh, body });
  }
}
build();

// Debug renderer: one LineSegments object whose buffers are refilled from world.debugRender().
const debugLines = new THREE.LineSegments(new THREE.BufferGeometry(), new THREE.LineBasicMaterial({ vertexColors: true }));
debugLines.visible = false;
debugLines.frustumCulled = false;
scene.add(debugLines);

renderer.domElement.addEventListener('pointerdown', () => {
  const first = pairs[0].body, rot = first.rotation();
  const push = new THREE.Vector3(0.6, 0, 0).applyQuaternion(new THREE.Quaternion(rot.x, rot.y, rot.z, rot.w));
  first.applyImpulseAtPoint({ x: push.x, y: 0, z: push.z }, { x: first.translation().x, y: 0.9, z: first.translation().z }, true);
});
addEventListener('keydown', (e) => {
  if (e.code === 'KeyD') debugLines.visible = !debugLines.visible;
  if (e.code === 'KeyR') build();
});

const timer = new THREE.Timer();
let acc = 0;
renderer.setAnimationLoop((t) => {
  timer.update(t);
  acc += Math.min(Math.max(timer.getDelta(), 0), 0.1);
  while (acc >= world.timestep) { world.step(); acc -= world.timestep; }   // fixed steps
  for (const { mesh, body } of pairs) {
    const p = body.translation(), q = body.rotation();
    mesh.position.set(p.x, p.y, p.z);
    mesh.quaternion.set(q.x, q.y, q.z, q.w);
  }
  if (debugLines.visible) {
    const { vertices, colors } = world.debugRender();
    debugLines.geometry.setAttribute('position', new THREE.BufferAttribute(vertices, 3));
    debugLines.geometry.setAttribute('color', new THREE.BufferAttribute(colors, 4));
  }
  renderer.render(scene, camera);
});
</script>

world.free() matters: Rapier objects live in WebAssembly memory, which the JavaScript garbage collector doesn't manage. Free a world (and anything else with a free() method, such as event queues and character controllers) when you replace it, or memory grows with every level restart.

Queries

Rapier answers geometric questions against colliders, much faster than Three.js's triangle raycasts:

js
const ray = new RAPIER.Ray({ x: 0, y: 5, z: 0 }, { x: 0, y: -1, z: 0 });   // direction normalized
const hit = world.castRay(ray, 10, true);           // max distance, solid
if (hit) {
  const point = ray.pointAt(hit.timeOfImpact);      // distance along the ray
  const collider = hit.collider;                    // what was hit
}
world.castRayAndGetNormal(ray, 10, true);           // also returns hit.normal
world.intersectionsWithPoint({ x, y, z }, (collider) => { /* … */ return true; });
world.castShape(/* … */);                           // sweep a shape: thick rays, "will I fit?"

Most queries accept filters (collision groups, a body to exclude) so a character's own collider doesn't block its ground check.

Rapier vs cannon-es

cannon-es Rapier
Language JavaScript Rust → WebAssembly
Speed fine for hundreds of bodies thousands of bodies
Determinism same JS engine & inputs designed for cross-platform determinism (same build)
Character controller no (build your own) yes (KinematicCharacterController)
CCD (fast objects) no yes (setCcdEnabled(true))
Memory garbage-collected manual free()
Debugging read the JS source debugRender()
Activity stable, rarely updated actively developed

Test yourself

What must you do before using @dimforge/rapier3d-compat?

  1. Call new RAPIER.World() twice
  2. await RAPIER.init() to load the WebAssembly module
  3. Install a browser plugin
  4. Nothing

Which body type should a moving platform use?

  1. dynamic
  2. fixed
  3. kinematicPositionBased
  4. a collider without a body

Why call world.free() when you rebuild a level?

  1. To reset gravity
  2. Rapier's objects live in WebAssembly memory that the JS garbage collector doesn't release
  3. It speeds up the next step
  4. Three.js requires it