TExcelTAD
Home › 3D Web Games with Three.js › Three.js Exercises

Three.js Exercises

Practice the logic behind 3D games. The first six exercises are pure functions (no WebGL), the kind of code where most game bugs live: smoothing, camera-relative input, angles, triggers, dynamic resolution, LOD. Each starter prints wrong answers until you complete the TODO; compare with the expected output and only then open the solution. The last exercise is playable.

Tip: Run the starter first to see what the tests print, then change the code and press Ctrl+Enter. The same functions appear in the lessons linked under each title if you get stuck.

Exercise 1: Frame-rate-independent smoothing

Topics: Third-Person Camera, exponential damping

Write smoothFactor(sharpness, dt): the factor to pass to lerp each frame so that following a target behaves the same at any frame rate. With a correct factor, the three lines report the same distance left. The last line checks the edge cases: no time passed means no movement, and an enormous sharpness means "arrive immediately".

js · try it yourself
function smoothFactor(sharpness, dt) {
  // TODO: the fraction of the remaining distance to close this frame, independent of the frame rate
  return 0.1;
}

// Follow a target 10 m away for 0.5 s at three frame rates: the distance left must match.
for (const fps of [30, 60, 144]) {
  let x = 0;
  for (let i = 0; i < fps / 2; i++) x += (10 - x) * smoothFactor(4, 1 / fps);
  console.log(`${String(fps).padStart(3)} fps: ${(10 - x).toFixed(3)} m left`);
}
console.log(smoothFactor(4, 0).toFixed(3), smoothFactor(1e9, 1 / 60).toFixed(3));

Expected output:

text
 30 fps: 1.353 m left
 60 fps: 1.353 m left
144 fps: 1.353 m left
0.000 1.000
Show solution
js
function smoothFactor(sharpness, dt) {
  return 1 - Math.exp(-sharpness * dt);
}

// Follow a target 10 m away for 0.5 s at three frame rates: the distance left must match.
for (const fps of [30, 60, 144]) {
  let x = 0;
  for (let i = 0; i < fps / 2; i++) x += (10 - x) * smoothFactor(4, 1 / fps);
  console.log(`${String(fps).padStart(3)} fps: ${(10 - x).toFixed(3)} m left`);
}
console.log(smoothFactor(4, 0).toFixed(3), smoothFactor(1e9, 1 / 60).toFixed(3));

Exercise 2: Camera-relative movement

Topics: First-Person Controls, Explorer 2

Return the ground-plane movement direction [x, z] for a camera yaw and WASD-style input, so that W always moves away from the camera. Diagonal input must not be faster than straight input.

js · try it yourself
// yaw: camera yaw in radians (0 = camera looks down -Z). f, s: input in -1..1 (forward, right).
function moveDir(yaw, f, s) {
  // TODO: forward is (-sin yaw, -cos yaw), right is (cos yaw, -sin yaw) on the ground plane.
  // Combine them with the input and normalize when the length exceeds 1.
  return [0, 0];
}

const fmt = ([x, z]) => `(${(Math.abs(x) < 5e-3 ? 0 : x).toFixed(2)}, ${(Math.abs(z) < 5e-3 ? 0 : z).toFixed(2)})`;
console.log(fmt(moveDir(0, 1, 0)));              // W, camera unrotated
console.log(fmt(moveDir(Math.PI / 2, 1, 0)));    // W, camera turned left 90°
console.log(fmt(moveDir(0, 1, 1)));              // W + D: diagonal, not faster
console.log(fmt(moveDir(Math.PI, 0, -1)));       // A, camera turned around
console.log(fmt(moveDir(0, 0, 0)));              // no input

Expected output:

text
(0.00, -1.00)
(-1.00, 0.00)
(0.71, -0.71)
(1.00, 0.00)
(0.00, 0.00)
Show solution
js
// yaw: camera yaw in radians (0 = camera looks down -Z). f, s: input in -1..1 (forward, right).
function moveDir(yaw, f, s) {
  let x = -Math.sin(yaw) * f + Math.cos(yaw) * s;
  let z = -Math.cos(yaw) * f - Math.sin(yaw) * s;
  const len = Math.hypot(x, z);
  if (len > 1) { x /= len; z /= len; }
  return [x, z];
}

const fmt = ([x, z]) => `(${(Math.abs(x) < 5e-3 ? 0 : x).toFixed(2)}, ${(Math.abs(z) < 5e-3 ? 0 : z).toFixed(2)})`;
console.log(fmt(moveDir(0, 1, 0)));              // W, camera unrotated
console.log(fmt(moveDir(Math.PI / 2, 1, 0)));    // W, camera turned left 90°
console.log(fmt(moveDir(0, 1, 1)));              // W + D: diagonal, not faster
console.log(fmt(moveDir(Math.PI, 0, -1)));       // A, camera turned around
console.log(fmt(moveDir(0, 0, 0)));              // no input

Exercise 3: Turning the short way

Topics: Quaternions & lookAt, angle wrapping

A character facing 10° that wants to face 350° should turn 20° clockwise, not 340° the other way. Write angleDelta(a, b) (the shortest signed difference, in the range (−π, π]) and turnTowards(current, target, maxStep) (turn at most maxStep toward the target, without overshooting).

js · try it yourself
// Shortest signed difference from angle a to angle b, in (-PI, PI].
function angleDelta(a, b) {
  // TODO: b - a, wrapped into (-PI, PI]
  return b - a;
}
// Turn from `current` toward `target` by at most `maxStep` radians.
function turnTowards(current, target, maxStep) {
  // TODO: step toward target along the shortest way, never further than maxStep and never past it
  return target;
}

const deg = (r) => `${(r * 180 / Math.PI).toFixed(0)}°`;
const rad = (d) => d * Math.PI / 180;
console.log(deg(angleDelta(rad(10), rad(350))));   // -20°, not +340°
console.log(deg(angleDelta(rad(350), rad(10))));   // +20°
console.log(deg(angleDelta(rad(90), rad(-90))));   // exactly opposite
console.log(deg(turnTowards(rad(170), rad(-170), rad(5))));   // crosses 180° the short way
console.log(deg(turnTowards(rad(0), rad(3), rad(5))));        // arrives, no overshoot

Expected output:

text
-20°
20°
180°
175°
3°
Show solution
js
// Shortest signed difference from angle a to angle b, in (-PI, PI].
function angleDelta(a, b) {
  let d = (b - a) % (2 * Math.PI);
  if (d > Math.PI) d -= 2 * Math.PI;
  if (d <= -Math.PI) d += 2 * Math.PI;
  return d;
}
// Turn from `current` toward `target` by at most `maxStep` radians.
function turnTowards(current, target, maxStep) {
  const d = angleDelta(current, target);
  return current + Math.sign(d) * Math.min(Math.abs(d), maxStep);
}

const deg = (r) => `${(r * 180 / Math.PI).toFixed(0)}°`;
const rad = (d) => d * Math.PI / 180;
console.log(deg(angleDelta(rad(10), rad(350))));   // -20°, not +340°
console.log(deg(angleDelta(rad(350), rad(10))));   // +20°
console.log(deg(angleDelta(rad(90), rad(-90))));   // exactly opposite
console.log(deg(turnTowards(rad(170), rad(-170), rad(5))));   // crosses 180° the short way
console.log(deg(turnTowards(rad(0), rad(3), rad(5))));        // arrives, no overshoot

Exercise 4: Trigger enter and exit

Topics: Triggers & Collision Events

Write the bookkeeping that physics engines do for sensors: given the player (a circle on the ground) and a list of circular zones, report each zone once when the player enters it and once when the player leaves it.

js · try it yourself
// Track which pickups the player overlaps, reporting enter/exit edges once.
function makeTrigger() {
  const inside = new Set();
  return function update(player, zones) {
    const events = [];
    for (const z of zones) {
      // TODO: circles overlap when the centre distance is less than the sum of the radii.
      // Push `enter <id>` when an overlap starts and `exit <id>` when it ends (use the `inside` set).
    }
    return events;
  };
}

const zones = [{ id: 'coin', x: 2, z: 0, r: 0.5 }, { id: 'water', x: 5, z: 0, r: 1.5 }];
const update = makeTrigger();
for (let step = 0; step <= 14; step++) {
  const player = { x: step * 0.5, z: 0, r: 0.4 };
  const ev = update(player, zones);
  if (ev.length) console.log(`x=${player.x.toFixed(1)}: ${ev.join(', ')}`);
}

Expected output:

text
x=1.5: enter coin
x=3.0: exit coin
x=3.5: enter water
x=7.0: exit water
Show solution
js
// Track which pickups the player overlaps, reporting enter/exit edges once.
function makeTrigger() {
  const inside = new Set();
  return function update(player, zones) {
    const events = [];
    for (const z of zones) {
      const overlap = Math.hypot(player.x - z.x, player.z - z.z) < player.r + z.r;
      if (overlap && !inside.has(z.id)) { inside.add(z.id); events.push(`enter ${z.id}`); }
      if (!overlap && inside.has(z.id)) { inside.delete(z.id); events.push(`exit ${z.id}`); }
    }
    return events;
  };
}

const zones = [{ id: 'coin', x: 2, z: 0, r: 0.5 }, { id: 'water', x: 5, z: 0, r: 1.5 }];
const update = makeTrigger();
for (let step = 0; step <= 14; step++) {
  const player = { x: step * 0.5, z: 0, r: 0.4 };
  const ev = update(player, zones);
  if (ev.length) console.log(`x=${player.x.toFixed(1)}: ${ev.join(', ')}`);
}

Exercise 5: Dynamic resolution

Topics: The Render Loop & Resizing, Field Notes

When the GPU is the bottleneck, frame time grows with the number of pixels, which grows with the square of the pixel ratio. Write chooseRatio(current, frameMs, budgetMs, deviceRatio): from the allowed steps (0.75, 1, 1.25, 1.5, 2, never above the device's own ratio), pick the largest one whose estimated frame time fits the budget.

js · try it yourself
// Pick a render scale (pixel ratio) that keeps the frame under budget.
// frameMs: measured GPU-bound frame time at the current ratio. Pixels scale with ratio².
function chooseRatio(current, frameMs, budgetMs, deviceRatio) {
  const steps = [0.75, 1, 1.25, 1.5, 2].filter((r) => r <= deviceRatio);
  // estimated frame time at ratio r: frameMs * (r / current)²
  // TODO: return the largest ratio in `steps` whose estimated frame time fits the budget
  // (or the smallest step if none fits)
  return current;
}

console.log(chooseRatio(2, 30, 14, 3));      // phone struggling at ratio 2
console.log(chooseRatio(1, 6, 14, 2));       // laptop with headroom
console.log(chooseRatio(1.5, 14, 14, 2));    // exactly on budget: keep it
console.log(chooseRatio(1, 80, 14, 1));      // very slow device: lowest step

Expected output:

text
1.25
1.5
1.5
0.75
Show solution
js
// Pick a render scale (pixel ratio) that keeps the frame under budget.
// frameMs: measured GPU-bound frame time at the current ratio. Pixels scale with ratio².
function chooseRatio(current, frameMs, budgetMs, deviceRatio) {
  const steps = [0.75, 1, 1.25, 1.5, 2].filter((r) => r <= deviceRatio);
  // estimated frame time at ratio r: frameMs * (r / current)²
  let best = steps[0];
  for (const r of steps) if (frameMs * (r / current) ** 2 <= budgetMs) best = r;
  return best;
}

console.log(chooseRatio(2, 30, 14, 3));      // phone struggling at ratio 2
console.log(chooseRatio(1, 6, 14, 2));       // laptop with headroom
console.log(chooseRatio(1.5, 14, 14, 2));    // exactly on budget: keep it
console.log(chooseRatio(1, 80, 14, 1));      // very slow device: lowest step

Exercise 6: LOD with hysteresis

Topics: LOD & Frustum Culling

Write the level choice that THREE.LOD makes, including its hysteresis: going to a coarser level happens at the threshold, but going back to a finer one only when the camera is 10% closer than the threshold, so an object at the boundary doesn't flicker.

js · try it yourself
// LOD level from distance, with hysteresis so a camera hovering at a boundary doesn't flicker.
// thresholds: distances where levels 1, 2, ... start. Switching back to a finer level needs (1 - h) * threshold.
function lodLevel(prevLevel, distance, thresholds, h) {
  // TODO: count how many thresholds the distance has passed (that's the plain level).
  // If that is finer than prevLevel, only switch when distance < threshold * (1 - h).
  return 0;
}

const thresholds = [20, 50];
let level = 0;
for (const d of [10, 19, 21, 19, 17, 30, 51, 48, 44, 60]) {
  level = lodLevel(level, d, thresholds, 0.1);
  console.log(`distance ${String(d).padStart(2)} -> level ${level}`);
}

Expected output:

text
distance 10 -> level 0
distance 19 -> level 0
distance 21 -> level 1
distance 19 -> level 1
distance 17 -> level 0
distance 30 -> level 1
distance 51 -> level 2
distance 48 -> level 2
distance 44 -> level 1
distance 60 -> level 2
Show solution
js
// LOD level from distance, with hysteresis so a camera hovering at a boundary doesn't flicker.
// thresholds: distances where levels 1, 2, ... start. Switching back to a finer level needs (1 - h) * threshold.
function lodLevel(prevLevel, distance, thresholds, h) {
  let level = 0;
  while (level < thresholds.length && distance >= thresholds[level]) level++;
  if (level < prevLevel && distance >= thresholds[prevLevel - 1] * (1 - h)) return prevLevel;   // not close enough yet
  return level;
}

const thresholds = [20, 50];
let level = 0;
for (const d of [10, 19, 21, 19, 17, 30, 51, 48, 44, 60]) {
  level = lodLevel(level, d, thresholds, 0.1);
  console.log(`distance ${String(d).padStart(2)} -> level ${level}`);
}

Exercise 7: Jump and collect (playable)

Topics: Character Controller (jump maths), Explorer 3

The capsule walks but can't jump, and the coins can't be collected. Complete the two TODOs in the update:

  1. Jump: on Space while standing on the ground, set the vertical speed; apply gravity every step; land back on the ground. With JUMP = 7 and GRAVITY = 20, the jump should peak about 7² / (2 · 20) ≈ 1.2 m up.
  2. Collect: hide a coin and count it when the player comes within 0.8 m of 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 to move, Space to jump</small></div>
<script type="module">
import * as THREE from 'three';

// ---- 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 ----

const scene = new THREE.Scene();
scene.background = new THREE.Color('#8fb8de');
const camera = new THREE.PerspectiveCamera(55, innerWidth / innerHeight, 0.1, 100);
camera.position.set(0, 7, 9);
camera.lookAt(0, 0, 0);
scene.add(new THREE.HemisphereLight('#fff', '#556644', 1.5));
const sun = new THREE.DirectionalLight('#fff', 2);
sun.position.set(3, 8, 4);
scene.add(sun);
const ground = new THREE.Mesh(new THREE.PlaneGeometry(16, 16), new THREE.MeshStandardMaterial({ color: '#6f9e58' }));
ground.rotation.x = -Math.PI / 2;
scene.add(ground);

const player = new THREE.Mesh(new THREE.CapsuleGeometry(0.35, 0.7, 4, 12), new THREE.MeshStandardMaterial({ color: '#ff7043' }));
player.position.y = 0.7;                       // capsule centre: radius + half its straight part
scene.add(player);
const coins = [[-4, -3], [3, -4], [5, 2], [-2, 4], [0, -1]].map(([x, z]) => {
  const c = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.3, 0.08, 24).rotateX(Math.PI / 2), new THREE.MeshStandardMaterial({ color: '#ffc928', emissive: '#4a3500' }));
  c.position.set(x, 0.7, z);
  scene.add(c);
  return c;
});
const hud = document.getElementById('hud');
let collected = 0, vy = 0;
const GROUND_Y = 0.7, GRAVITY = 20, JUMP = 7;

run(scene, camera, (dt) => {
  const x = (keys.has('KeyD') || keys.has('ArrowRight') ? 1 : 0) - (keys.has('KeyA') || keys.has('ArrowLeft') ? 1 : 0);
  const z = (keys.has('KeyS') || keys.has('ArrowDown') ? 1 : 0) - (keys.has('KeyW') || keys.has('ArrowUp') ? 1 : 0);
  const len = Math.hypot(x, z) || 1;
  player.position.x = THREE.MathUtils.clamp(player.position.x + (x / len) * 5 * dt, -7.5, 7.5);
  player.position.z = THREE.MathUtils.clamp(player.position.z + (z / len) * 5 * dt, -7.5, 7.5);

  // TODO 1: jumping. When Space is pressed (pressed.has('Space')) and the player stands on the ground
  // (player.position.y <= GROUND_Y), set vy = JUMP. Every step, apply gravity to vy, move player.position.y
  // by vy * dt, and when it drops below GROUND_Y, put it back on the ground and set vy = 0.

  for (const c of coins) {
    if (!c.visible) continue;
    c.rotation.y += 2 * dt;
    // TODO 2: collect the coin when the player is closer than 0.8 m to it (player.position.distanceTo(c.position)):
    // hide it (c.visible = false) and count it in `collected`.
  }
  hud.textContent = collected === coins.length ? 'All coins collected!' : `Coins ${collected} / ${coins.length}`;
});
</script>

When it works, the HUD counts the coins and shows "All coins collected!" at the end. Jumping doesn't help with these coins yet; as an extension, raise two of them to y = 1.8 so they need a jump.

Show solution

The new part of the update (replace the two TODO blocks):

js
  if (pressed.has('Space') && player.position.y <= GROUND_Y) vy = JUMP;
  vy -= GRAVITY * dt;
  player.position.y += vy * dt;
  if (player.position.y < GROUND_Y) { player.position.y = GROUND_Y; vy = 0; }

  for (const c of coins) {
    if (!c.visible) continue;
    c.rotation.y += 2 * dt;
    if (player.position.distanceTo(c.position) < 0.8) { c.visible = false; collected++; }
  }

Where to go next

Test yourself

With smoothFactor = 1 - Math.exp(-4 * dt), a follower is 10 m behind a still target. Roughly how far behind is it after 0.5 s, at any frame rate?

  1. 0 m
  2. about 1.35 m
  3. about 5 m
  4. it depends on the frame rate

angleDelta(10°, 350°) should return:

  1. +340°
  2. −20°
  3. +20°
  4. −340°

A GPU-bound frame takes 30 ms at pixel ratio 2. Estimated time at ratio 1?

  1. 15 ms
  2. 7.5 ms
  3. 30 ms
  4. 60 ms