TExcelTAD
Home › 3D Web Games with Three.js › Explorer 2: Follow Camera & Collision

Explorer 2: Follow Camera & Collision

In the first step the explorer walked through trees and the camera lost sight of it behind every trunk. This step adds the two systems that make a 3D game feel solid:

  1. Physics collisions with Rapier: every piece of scenery gets a collider, and the hero becomes a kinematic capsule moved by Rapier's character controller (sliding along walls, climbing the stairs, walking up the ramp, jumping onto the third plateau).
  2. An orbit follow camera: drag to turn the camera around the hero, scroll to zoom, movement is camera-relative, and a ray keeps the camera in front of walls and trunks.

Colliders for the scenery

Because every static object was created through solid(), giving the whole level collision is a change in one place. solid now takes a collider description, places it at the mesh's position and rotation, and also records the mesh in blockers, the list the camera ray tests:

js
function solid(mesh, colliderDesc) {
  mesh.castShadow = mesh.receiveShadow = true;
  scene.add(mesh);
  blockers.push(mesh);
  world.createCollider(colliderDesc.setTranslation(mesh.position.x, mesh.position.y, mesh.position.z)
    .setRotation(mesh.quaternion));
}

Each call site picks a simple shape that matches the mesh closely enough: cuboids for walls, plateaus, stairs and the ramp (with the same rotation as the mesh), cylinders for tree trunks (slightly wider than the trunk, so the hero doesn't brush against the leaves), and balls for rocks. Nothing collides against the actual triangles, which keeps physics fast and stable. The leaves have no collider, so you can walk "under" the trees. The boundary wall's collider is taller than the 1 m wall you see, so a jump can't clear it: invisible collision is a normal level-design tool.

The hero as a character controller

The hero's physics body is a kinematic capsule (0.5 m half-height, 0.32 m radius) with a KinematicCharacterController, set up as in the Character Controller lesson:

  • enableAutostep(0.45, 0.2, false) climbs the 0.4 m stairs;
  • setMaxSlopeClimbAngle(40°) allows the 21° ramp;
  • enableSnapToGround(0.3) keeps the hero grounded walking down;
  • gravity 22 m/s² and a jump speed of 8 m/s give a jump of 8² / (2 · 22) ≈ 1.45 m, enough for the 1.1 m plateau but not the 1.6 m or 2.4 m ones, which need the stairs and the ramp.

The visual hero is positioned from the body each step, lowered by FOOT (half-height + radius) because the capsule's origin is its centre and the model's origin is between its feet. While airborne, the walk cycle freezes into a jump pose.

Camera-relative movement and the orbit camera

Once the camera can turn, "W moves toward −Z" becomes confusing; players expect W to move away from the camera. The input is therefore rotated by the camera's yaw, exactly as in First-Person Controls:

js
let mx = -Math.sin(camYaw) * f + Math.cos(camYaw) * s;
let mz = -Math.cos(camYaw) * f - Math.sin(camYaw) * s;

The camera stores camYaw, camPitch and camDist, changed by dragging and the mouse wheel. Each step it computes the wanted position on a sphere around a point 1.4 m above the hero's feet, then casts a ray from that point toward the camera against blockers. If the ray hits a trunk or a wall before reaching the camera distance, the camera snaps in front of it; otherwise it eases toward its wanted position. This is the Third-Person Camera lesson's camera, now inside a real level.

Play it

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; overflow: hidden; background: #0e1018; }
  canvas { display: block; outline: none; touch-action: none; }
  #hud { position: fixed; left: 10px; top: 8px; color: #fff; font: 13px system-ui, sans-serif; pointer-events: none; text-shadow: 0 1px 2px #000; }
  #veil { position: fixed; inset: 0; display: grid; place-content: center; background: rgba(0, 0, 0, 0.55); color: #fff; font: 600 20px system-ui, sans-serif; text-align: center; pointer-events: none; }
  #veil small { display: block; margin-top: 6px; font-weight: 400; font-size: 13px; }
  #veil.off { display: none; }
</style>
<div id="hud"></div>
<div id="veil">Click to play<small>WASD move, Space jump, drag to look, wheel to zoom</small></div>
<script type="module">
import * as THREE from 'three';
import RAPIER from '@dimforge/rapier3d-compat';
await RAPIER.init();

// ---- 3D play kit: renderer, click to focus, keys, pause on blur, fixed-step loop ----
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.prepend(renderer.domElement);
const cv = renderer.domElement, veil = document.getElementById('veil');
const keys = new Set(), pressed = new Set();   // held now / pressed since the last update
let active = false, drawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; veil.classList.add('off'); });
cv.addEventListener('blur', () => { active = false; drawn = false; veil.classList.remove('off'); keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault();   // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function run(scene, camera, update) {
  const STEP = 1 / 60, timer = new THREE.Timer();
  let acc = 0;
  addEventListener('resize', () => {
    camera.aspect = innerWidth / innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(innerWidth, innerHeight);
    drawn = false;
  });
  renderer.setAnimationLoop((t) => {
    timer.update(t);
    if (active) {
      acc += Math.min(timer.getDelta(), 0.1);
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
    } else if (drawn) return;          // paused: the last frame stays on screen
    renderer.render(scene, camera);
    drawn = true;
  });
}
// ---- end of play kit ----

// ---------- seeded random numbers ----------
function mulberry32(seed) {
  return () => {
    seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
const rng = mulberry32(2024);

// ---------- scene, lights ----------
renderer.shadowMap.enabled = true;
const scene = new THREE.Scene();
scene.background = new THREE.Color('#9fc6ea');
scene.fog = new THREE.Fog('#9fc6ea', 25, 70);
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 150);
scene.add(new THREE.HemisphereLight('#e4f0ff', '#58704a', 1.4));
const sun = new THREE.DirectionalLight('#fff3dd', 2.4);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
Object.assign(sun.shadow.camera, { left: -14, right: 14, top: 14, bottom: -14, near: 1, far: 60 });
sun.shadow.normalBias = 0.03;
scene.add(sun, sun.target);
const SUN_OFFSET = new THREE.Vector3(-12, 20, 8);

// ---------- physics world ----------
const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 });
const blockers = [];                               // meshes the camera must not pass through

function solid(mesh, colliderDesc) {               // a static mesh + its fixed collider
  mesh.castShadow = mesh.receiveShadow = true;
  scene.add(mesh);
  blockers.push(mesh);
  world.createCollider(colliderDesc.setTranslation(mesh.position.x, mesh.position.y, mesh.position.z)
    .setRotation(mesh.quaternion));
}

// ---------- the world ----------
const HALF = 30;                                   // the meadow spans -30..30
const ground = new THREE.Mesh(new THREE.PlaneGeometry(HALF * 2, HALF * 2), new THREE.MeshStandardMaterial({ color: '#6f9e58' }));
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
world.createCollider(RAPIER.ColliderDesc.cuboid(HALF, 0.5, HALF).setTranslation(0, -0.5, 0));
const stone = new THREE.MeshStandardMaterial({ color: '#a39a8a', roughness: 0.9 });
for (const [x, z, w, d] of [[0, -HALF, HALF * 2, 1], [0, HALF, HALF * 2, 1], [-HALF, 0, 1, HALF * 2], [HALF, 0, 1, HALF * 2]]) {
  const wall = new THREE.Mesh(new THREE.BoxGeometry(w, 1, d), stone);
  wall.position.set(x, 0.5, z);
  solid(wall, RAPIER.ColliderDesc.cuboid(w / 2, 2, d / 2));   // the collider is taller than it looks
}

// Plateaus: one with stairs, one with a ramp, one you must jump onto.
const rock = new THREE.MeshStandardMaterial({ color: '#8d8577', roughness: 0.95 });
function box(w, h, d, x, y, z, mat, rotX = 0) {
  const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat);
  m.position.set(x, y, z);
  m.rotation.x = rotX;
  solid(m, RAPIER.ColliderDesc.cuboid(w / 2, h / 2, d / 2));
  return m;
}
box(6, 1.6, 6, -16, 0.8, -14, rock);                                   // plateau A, top 1.6
for (let i = 0; i < 4; i++) box(2, 0.4 * (i + 1), 1, -16, 0.2 * (i + 1), -8.5 - i, rock);   // its stairs
box(6, 2.4, 6, 16, 1.2, -14, rock);                                    // plateau B, top 2.4
box(2.5, 0.3, 7, 16, 1.15, -7.6, rock, 0.37);                           // its ramp (~21°)
box(4, 1.1, 4, 15, 0.55, 14, rock);                                    // plateau C, top 1.1: jump

// Ruins around the shrine.
for (const [x, z, w, d] of [[-5, -5, 4, 0.6], [5, -5, 4, 0.6], [-5, 5, 0.6, 4], [5, 5, 0.6, 3]]) box(w, 1.8, d, x, 0.9, z, stone);

// Trees and rocks, scattered with the seeded RNG, away from the important places.
const keepClear = [[0, 0, 8], [-16, -12, 6], [16, -11, 6], [15, 14, 4]];
function freeSpot(margin) {
  for (;;) {
    const x = (rng() * 2 - 1) * (HALF - 3), z = (rng() * 2 - 1) * (HALF - 3);
    if (keepClear.every(([cx, cz, r]) => Math.hypot(x - cx, z - cz) > r + margin)) return [x, z];
  }
}
const trunkGeo = new THREE.CylinderGeometry(0.2, 0.3, 1.6, 8);
const leafGeo = new THREE.ConeGeometry(1.3, 3, 8);
const trunkMat = new THREE.MeshStandardMaterial({ color: '#6b4a2b' });
const leafMat = new THREE.MeshStandardMaterial({ color: '#2f6e3a', flatShading: true });
for (let i = 0; i < 34; i++) {
  const [x, z] = freeSpot(1.5);
  const s = 0.8 + rng() * 0.6;
  const trunk = new THREE.Mesh(trunkGeo, trunkMat);
  trunk.position.set(x, 0.8 * s, z);
  trunk.scale.setScalar(s);
  const leaves = new THREE.Mesh(leafGeo, leafMat);
  leaves.position.set(x, (1.6 + 1.3) * s, z);
  leaves.scale.setScalar(s);
  leaves.castShadow = true;
  scene.add(leaves);
  solid(trunk, RAPIER.ColliderDesc.cylinder(0.8 * s, 0.35 * s));
}
const rockGeo = new THREE.IcosahedronGeometry(1, 0);
for (let i = 0; i < 14; i++) {
  const [x, z] = freeSpot(1.5);
  const r = 0.5 + rng() * 0.8;
  const m = new THREE.Mesh(rockGeo, rock);
  m.position.set(x, r * 0.5, z);
  m.scale.setScalar(r);
  m.rotation.set(rng() * 3, rng() * 3, 0);
  solid(m, RAPIER.ColliderDesc.ball(r * 0.9));
}

// ---------- the hero: a little explorer built from primitives ----------
const hero = new THREE.Group();
const skin = new THREE.MeshStandardMaterial({ color: '#f1c27d' });
const cloth = new THREE.MeshStandardMaterial({ color: '#e86a3a' });
const dark = new THREE.MeshStandardMaterial({ color: '#3b3f4a' });
const torso = new THREE.Mesh(new THREE.CapsuleGeometry(0.28, 0.45, 4, 12), cloth);
torso.position.y = 1.0;
const head = new THREE.Mesh(new THREE.SphereGeometry(0.22, 16, 12), skin);
head.position.y = 1.55;
const pack = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.45, 0.2), dark);
pack.position.set(0, 1.05, -0.3);
function limb(w, h, x, y, mat) {                    // a box hanging from a pivot at its top
  const pivot = new THREE.Group();
  pivot.position.set(x, y, 0);
  const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, w), mat);
  m.position.y = -h / 2;
  m.castShadow = true;
  pivot.add(m);
  hero.add(pivot);
  return pivot;
}
const legL = limb(0.16, 0.6, -0.13, 0.62, dark), legR = limb(0.16, 0.6, 0.13, 0.62, dark);
const armL = limb(0.12, 0.5, -0.38, 1.3, cloth), armR = limb(0.12, 0.5, 0.38, 1.3, cloth);
for (const m of [torso, head, pack]) m.castShadow = true;
hero.add(torso, head, pack);
scene.add(hero);

// Physics body for the hero: a kinematic capsule driven by Rapier's character controller.
const CAPSULE_HALF = 0.5, CAPSULE_R = 0.32, FOOT = CAPSULE_HALF + CAPSULE_R;   // centre is FOOT above the ground
const START = new THREE.Vector3(0, FOOT + 0.05, 9);
const heroBody = world.createRigidBody(RAPIER.RigidBodyDesc.kinematicPositionBased().setTranslation(START.x, START.y, START.z));
const heroCol = world.createCollider(RAPIER.ColliderDesc.capsule(CAPSULE_HALF, CAPSULE_R), heroBody);
const controller = world.createCharacterController(0.02);
controller.enableAutostep(0.45, 0.2, false);
controller.enableSnapToGround(0.3);
controller.setMaxSlopeClimbAngle(THREE.MathUtils.degToRad(40));

// ---------- camera: orbit with the mouse, follow with damping, avoid walls ----------
let camYaw = 0, camPitch = 0.45, camDist = 7;
cv.addEventListener('pointermove', (e) => {
  if (!active || !(e.buttons & 1)) return;
  camYaw -= e.movementX * 0.005;
  camPitch = THREE.MathUtils.clamp(camPitch + e.movementY * 0.004, 0.05, 1.2);
});
cv.addEventListener('wheel', (e) => { e.preventDefault(); camDist = THREE.MathUtils.clamp(camDist + e.deltaY * 0.005, 3, 12); }, { passive: false });
const raycaster = new THREE.Raycaster();
const lookAt = new THREE.Vector3(), camDir = new THREE.Vector3(), camWanted = new THREE.Vector3();
function updateCamera(dt, snap = false) {
  lookAt.set(hero.position.x, hero.position.y + 1.4, hero.position.z);
  camDir.set(Math.sin(camYaw) * Math.cos(camPitch), Math.sin(camPitch), Math.cos(camYaw) * Math.cos(camPitch));
  raycaster.set(lookAt, camDir);
  raycaster.far = camDist;
  const hit = raycaster.intersectObjects(blockers, false)[0];
  const dist = hit ? Math.max(1, hit.distance - 0.3) : camDist;
  camWanted.copy(lookAt).addScaledVector(camDir, dist);
  if (snap || hit) camera.position.copy(camWanted);
  else camera.position.lerp(camWanted, 1 - Math.exp(-8 * dt));
  camera.lookAt(lookAt);
}

// ---------- game state ----------
const hud = document.getElementById('hud');
let vy = 0, grounded = false, heroYaw = 0, walkPhase = 0;

// ---------- the update ----------
const GRAVITY = 22, JUMP = 8, SPEED = 5.5;
run(scene, camera, (dt) => {

  // Camera-relative input.
  const f = (keys.has('KeyW') || keys.has('ArrowUp') ? 1 : 0) - (keys.has('KeyS') || keys.has('ArrowDown') ? 1 : 0);
  const s = (keys.has('KeyD') || keys.has('ArrowRight') ? 1 : 0) - (keys.has('KeyA') || keys.has('ArrowLeft') ? 1 : 0);
  let mx = -Math.sin(camYaw) * f + Math.cos(camYaw) * s, mz = -Math.cos(camYaw) * f - Math.sin(camYaw) * s;
  const len = Math.hypot(mx, mz);
  if (len > 1) { mx /= len; mz /= len; }

  if (grounded) vy = Math.max(vy, -1);
  if (grounded && pressed.has('Space')) vy = JUMP;
  vy -= GRAVITY * dt;
  controller.computeColliderMovement(heroCol, { x: mx * SPEED * dt, y: vy * dt, z: mz * SPEED * dt });
  const m = controller.computedMovement();
  grounded = controller.computedGrounded();
  if (grounded && vy < 0) vy = 0;
  const p = heroBody.translation();
  heroBody.setNextKinematicTranslation({ x: p.x + m.x, y: p.y + m.y, z: p.z + m.z });
  world.step();

  // Visuals: position, facing, walk cycle.
  const q = heroBody.translation();
  hero.position.set(q.x, q.y - FOOT, q.z);
  if (len > 0.01) {
    let diff = Math.atan2(mx, mz) - heroYaw;
    diff = Math.atan2(Math.sin(diff), Math.cos(diff));
    heroYaw += diff * (1 - Math.exp(-14 * dt));
    hero.rotation.y = heroYaw;
  }
  walkPhase += grounded ? Math.min(len, 1) * dt * 11 : 0;
  const swing = grounded ? Math.sin(walkPhase) * 0.7 * Math.min(len, 1) : 0.5;
  legL.rotation.x = swing; legR.rotation.x = grounded ? -swing : -0.3;
  armL.rotation.x = -swing * 0.8; armR.rotation.x = swing * 0.8;

  sun.target.position.copy(hero.position);
  sun.position.copy(hero.position).add(SUN_OFFSET);
  updateCamera(dt);
  hud.textContent = `${grounded ? 'grounded' : 'in the air'}   camera ${camera.position.distanceTo(lookAt).toFixed(1)} m`;
});

// First frame: place everything.
const q0 = heroBody.translation();
hero.position.set(q0.x, q0.y - FOOT, q0.z);
sun.target.position.copy(hero.position);
sun.position.copy(hero.position).add(SUN_OFFSET);
updateCamera(0, true);
</script>

Things to try in the level:

  • Walk into a tree at an angle: the controller slides you around it instead of stopping you.
  • Climb the stairs to the left plateau and the ramp to the right one. Try jumping onto the 2.4 m plateau directly: you can't.
  • Jump onto the low plateau at the front right.
  • Stand next to a wall and orbit the camera behind it: it pulls in instead of looking through.

Order of operations in a physics game

The update now follows a fixed order, which every engine's character code shares:

# Step Why here
1 read input, compute desired movement input belongs to this step
2 character controller: corrected movement, setNextKinematicTranslation before the physics step, so the step can use it
3 world.step() moves kinematic bodies, simulates dynamic ones
4 copy physics positions to meshes, animate the model after physics, so visuals show the new state
5 move the shadow box, update the camera last: they follow everything else

Getting this order wrong produces the classic one-frame lag jitter: a camera that reads the hero's position before physics moved it is always one step behind and shakes when the speed changes.

Test yourself

Why does the boundary wall's collider extend much higher than the visible wall?

  1. Rapier requires tall colliders
  2. So the player can't jump over the edge of the level; invisible collision is a normal level-design tool
  3. To make shadows longer
  4. It is a mistake

With gravity 22 m/s² and a jump speed of 8 m/s, roughly how high can the hero jump?

  1. 0.7 m
  2. 1.45 m
  3. 2.9 m
  4. 8 m

Why does the camera update come after world.step() and the mesh sync?

  1. Cameras can't be updated before physics
  2. Otherwise it follows last step's position and lags one frame behind, which shows as jitter
  3. To save draw calls
  4. Rapier requires it