Physics with cannon-es
Three.js draws things; it doesn't know about mass, gravity or collisions. For falling crates, rolling balls, ragdolls and vehicles you add a physics engine and keep two worlds side by side: the physics world simulates bodies with simple shapes, and every frame you copy each body's position and rotation onto its mesh. cannon-es is a pure-JavaScript engine (the pmndrs collective's modernised fork of the original cannon.js; 0.20.0 has been its latest release for a long time): easy to read and debug, small, and fine for a few hundred bodies. The next lesson covers Rapier, a faster WebAssembly engine.
The pieces
| cannon-es | Role | Three.js counterpart |
|---|---|---|
World |
holds bodies, gravity, solver; world.step() advances time |
Scene |
Body |
a rigid body: mass, position, quaternion, velocity, type |
Mesh |
Shape (Sphere, Box, Plane, Cylinder, ConvexPolyhedron, Heightfield, Trimesh) |
the collision geometry, attached to a body | BufferGeometry |
Material, ContactMaterial |
friction and restitution (bounciness) for pairs of materials | Material (only the name is similar) |
Body types: dynamic (mass > 0, moved by forces), static (mass: 0 or type: CANNON.Body.STATIC, never moves: floors, walls) and kinematic (moved by your code with a velocity, pushes dynamic bodies: moving platforms).
import * as CANNON from 'cannon-es';
const world = new CANNON.World({ gravity: new CANNON.Vec3(0, -9.82, 0) });
const ground = new CANNON.Body({ type: CANNON.Body.STATIC, shape: new CANNON.Plane() });
ground.quaternion.setFromEuler(-Math.PI / 2, 0, 0); // planes face +Z; turn it to face up
world.addBody(ground);
const ball = new CANNON.Body({ mass: 1, shape: new CANNON.Sphere(0.5), position: new CANNON.Vec3(0, 5, 0) });
world.addBody(ball);Note:
CANNON.Boxtakes half extents: a 1 × 1 × 1 crate isnew CANNON.Box(new CANNON.Vec3(0.5, 0.5, 0.5)), whileTHREE.BoxGeometry(1, 1, 1)takes full sizes. Mixing them up gives boxes that sink halfway into each other or float.
Stepping: fixed time, deterministic results
world.step(dt) with a single argument advances exactly one step of dt seconds. Called a fixed number of times, the simulation always produces the same numbers, which makes it testable. This example drops a bouncy ball and prints its height every 0.25 s (the output appears under the frame):
<script type="module">
import * as CANNON from 'cannon-es';
const world = new CANNON.World({ gravity: new CANNON.Vec3(0, -9.82, 0) });
const rubber = new CANNON.Material('rubber');
const concrete = new CANNON.Material('concrete');
world.addContactMaterial(new CANNON.ContactMaterial(rubber, concrete, { friction: 0.4, restitution: 0.7 }));
const ground = new CANNON.Body({ type: CANNON.Body.STATIC, shape: new CANNON.Plane(), material: concrete });
ground.quaternion.setFromEuler(-Math.PI / 2, 0, 0);
world.addBody(ground);
const ball = new CANNON.Body({ mass: 1, shape: new CANNON.Sphere(0.5), position: new CANNON.Vec3(0, 3, 0), material: rubber });
world.addBody(ball);
for (let i = 1; i <= 120; i++) {
world.step(1 / 60); // exactly one fixed step
if (i % 15 === 0) console.log(`t=${(i / 60).toFixed(2)}s y=${ball.position.y.toFixed(3)} vy=${ball.velocity.y.toFixed(2)}`);
}
</script>The console shows the ball falling, bouncing at about 70% of its speed, and bouncing again lower:
t=0.25s y=2.673 vy=-2.45
t=0.50s y=1.734 vy=-4.90
t=0.75s y=0.602 vy=5.20
t=1.00s y=1.573 vy=2.73
t=1.25s y=1.928 vy=0.28
t=1.50s y=1.670 vy=-2.18
t=1.75s y=0.799 vy=-4.62
t=2.00s y=0.986 vy=2.03In a game you don't step a fixed number of times; you feed real time in. world.step(fixedStep, deltaTime, maxSubSteps) does the accumulator for you: it runs as many fixed steps as fit into the elapsed time (at most maxSubSteps) and interpolates body positions for rendering (body.interpolatedPosition). Alternatively, call world.step(1 / 60) from your own fixed-step loop, as the course's play kit does. (world.fixedStep() reads the wall clock itself, so its results vary from run to run.)
Syncing meshes with bodies
// after stepping:
for (const { mesh, body } of pairs) {
mesh.position.copy(body.position); // CANNON.Vec3 has x, y, z, so THREE's copy() accepts it
mesh.quaternion.copy(body.quaternion); // same for x, y, z, w
}Never move a dynamic body by setting the mesh; the next sync overwrites it. Move the body: set body.velocity, apply forces (applyForce, applyImpulse), or for a teleport set body.position and reset body.velocity.
A tower to knock over
Click anywhere to throw a ball from the camera toward the point you clicked. R rebuilds the tower. Bodies that stop moving go to sleep (they turn darker) and cost almost nothing until something hits them.
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block; cursor: crosshair }
#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 throw, R to reset</div>
<script type="module">
import * as THREE from 'three';
import * as CANNON from 'cannon-es';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#a7c4e2');
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 100);
camera.position.set(2, 3.5, 8);
camera.lookAt(0, 2, 0);
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
scene.add(new THREE.HemisphereLight('#e8f1ff', '#5a5040', 1.3));
const sun = new THREE.DirectionalLight('#fff', 2.5);
sun.position.set(-5, 10, 6);
sun.castShadow = true;
Object.assign(sun.shadow.camera, { left: -8, right: 8, top: 8, bottom: -8 });
scene.add(sun);
const world = new CANNON.World({ gravity: new CANNON.Vec3(0, -9.82, 0) });
world.broadphase = new CANNON.SAPBroadphase(world); // faster than the naive default for many bodies
world.allowSleep = true;
const floorMesh = new THREE.Mesh(new THREE.PlaneGeometry(40, 40), new THREE.MeshStandardMaterial({ color: '#6f8f5f' }));
floorMesh.rotation.x = -Math.PI / 2;
floorMesh.receiveShadow = true;
scene.add(floorMesh);
const floorBody = new CANNON.Body({ type: CANNON.Body.STATIC, shape: new CANNON.Plane() });
floorBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0);
world.addBody(floorBody);
const pairs = [];
const boxGeo = new THREE.BoxGeometry(1, 0.5, 0.5);
const ballGeo = new THREE.SphereGeometry(0.35, 24, 12);
const ballMat = new THREE.MeshStandardMaterial({ color: '#455a64', metalness: 0.3, roughness: 0.4 });
function add(mesh, body) {
mesh.castShadow = mesh.receiveShadow = true;
scene.add(mesh);
world.addBody(body);
pairs.push({ mesh, body });
}
function clear() {
for (const { mesh, body } of pairs) { scene.remove(mesh); world.removeBody(body); if (mesh.geometry !== boxGeo && mesh.geometry !== ballGeo) mesh.geometry.dispose(); }
pairs.length = 0;
}
function buildTower() {
clear();
for (let level = 0; level < 8; level++) {
for (let i = 0; i < 3; i++) {
const along = level % 2 === 0; // alternate the direction of each layer, Jenga style
const offset = (i - 1) * 0.52;
const mesh = new THREE.Mesh(boxGeo, new THREE.MeshStandardMaterial({ color: new THREE.Color().setHSL(0.08 + level * 0.02, 0.6, 0.55) }));
const body = new CANNON.Body({
mass: 1,
shape: new CANNON.Box(new CANNON.Vec3(0.5, 0.25, 0.25)), // half extents!
position: new CANNON.Vec3(along ? offset : 0, 0.25 + level * 0.5, along ? 0 : offset),
});
if (along) body.quaternion.setFromEuler(0, Math.PI / 2, 0);
body.sleepSpeedLimit = 0.2;
add(mesh, body);
}
}
}
buildTower();
const raycaster = new THREE.Raycaster(), pointer = new THREE.Vector2();
renderer.domElement.addEventListener('pointerdown', (e) => {
pointer.set((e.offsetX / innerWidth) * 2 - 1, -(e.offsetY / innerHeight) * 2 + 1);
raycaster.setFromCamera(pointer, camera);
const dir = raycaster.ray.direction;
const body = new CANNON.Body({ mass: 4, shape: new CANNON.Sphere(0.35), position: new CANNON.Vec3().copy(camera.position) });
body.velocity.set(dir.x * 22, dir.y * 22 + 2, dir.z * 22); // throw along the click ray
add(new THREE.Mesh(ballGeo, ballMat), body);
});
addEventListener('keydown', (e) => { if (e.code === 'KeyR') buildTower(); });
const timer = new THREE.Timer();
renderer.setAnimationLoop((t) => {
timer.update(t);
const dt = Math.min(Math.max(timer.getDelta(), 0), 0.1);
world.step(1 / 60, dt, 5); // fixed 60 Hz steps, up to 5 per frame
for (const { mesh, body } of pairs) {
mesh.position.copy(body.interpolatedPosition);
mesh.quaternion.copy(body.interpolatedQuaternion);
if (mesh.material !== ballMat) mesh.material.emissive.setScalar(body.sleepState === CANNON.Body.SLEEPING ? 0 : 0.08);
}
renderer.render(scene, camera);
});
</script>Settings that matter
| Setting | Effect |
|---|---|
world.broadphase = new CANNON.SAPBroadphase(world) |
sweep-and-prune pair finding; much faster than the default NaiveBroadphase with many bodies |
world.allowSleep, body.sleepSpeedLimit, body.sleepTimeLimit |
resting bodies stop simulating until woken |
world.solver.iterations (default 10) |
more iterations = stiffer stacks and joints, more CPU |
world.defaultContactMaterial.friction / restitution |
defaults for pairs without a ContactMaterial |
body.linearDamping, angularDamping |
air resistance; stops things rolling forever |
body.fixedRotation = true (then updateMassProperties()) |
no tipping over: capsule characters |
body.collisionFilterGroup / collisionFilterMask |
bit masks: which groups collide with which |
body.addEventListener('collide', fn) |
contact callbacks (sounds, damage) |
Keeping physics stable
- Use simple shapes. Spheres and boxes are fastest and most stable. Approximate complex meshes with a few primitives added to one body (
body.addShape(shape, offset)).Trimeshonly collides reliably with spheres and planes; useConvexPolyhedronor compound shapes for dynamic objects. - Keep sizes and masses sensible. Metre scale, masses within a ratio of about 1:100 in a stack. A 1000 kg box on a 0.1 kg box will jitter or sink.
- Fast, small objects tunnel. A bullet moving 1 m per step can skip a 0.1 m wall. Use raycasts for bullets instead of bodies.
- Don't scale meshes to resize bodies. Shapes have their own sizes; scaling the mesh doesn't change the collider.
Test yourself
Which cannon-es shape matches new THREE.BoxGeometry(2, 1, 4)?
new CANNON.Box(new CANNON.Vec3(2, 1, 4))new CANNON.Box(new CANNON.Vec3(1, 0.5, 2))new CANNON.Box(2, 1, 4)new CANNON.Plane(2, 4)
What does world.step(1 / 60, dt, 5) do?
- Steps once by
dt - Runs as many fixed 1/60 s steps as fit into
dt(at most 5) and updates interpolated positions - Steps 5 times regardless of time
- Sets the frame rate to 60
You move a crate by setting crateMesh.position.x += 1, but it jumps back. Why?
- The mesh is static
- The sync step copies the body's position onto the mesh every frame; move the body instead
- Three.js locks positions of shadow casters
- The broadphase reset it