Week 10 Lab Sheet — 3D Collision Detection

Web Games Development · Collision detection · ~150 minutes

Objectives

  1. Describe an object with an axis-aligned bounding box, THREE.Box3 (min and max corners).
  2. Build boxes with setFromObject and setFromCenterAndSize.
  3. Test whether two boxes overlap with intersectsBox.
  4. Block movement at walls by moving and testing one axis at a time (sliding).
  5. Collect pick-ups: detect, remove from the scene and the array, and score.
  6. Move hazards on patrol paths and handle lives with a short invulnerability time.
  7. Build a level from a text map (an array of strings).
  8. Debug collisions by showing boxes with Box3Helper.

Instructions

Set up a Week10 npm project (step 1), keep npx vite running, and open each file at http://localhost:5173/ followed by its name. Build the example files, then the game, writing the code shown. Save after each step and watch the browser reload. Tick each checkpoint.

Files

1. Set up your Week10 project npm · Vite

Week10\

  1. Create a folder named Week10, open it in VS Code, and open the terminal with Ctrl+`.
  2. Create the project and install Three.js and Vite (the same commands as Week 7):
    npm init -y
    npm install three@0.170.0
    npm install --save-dev vite@5
  3. Shortcut: download package.json from Materials for this week into the folder, then run npm install instead.
  4. Start the Vite dev server and leave it running. Open the address it prints plus a file name, for example http://localhost:5173/box3.html. Press Ctrl+C in the terminal to stop it.
    npx vite
Checkpoint: the folder has package.json and node_modules, and npx vite shows Local: http://localhost:5173/.

2. box3.html Concept 1 · Bounding boxes

Week10\box3.html

  1. Create box3.html and add this code. The yellow box is recalculated every frame. Notice it never tilts: it grows instead.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>A Box Around a Spinning Shape</title>
    <style>
      body { margin: 0; overflow: hidden; background: #fffdf8; font-family: monospace; }
      #info { position: absolute; left: 16px; top: 12px; font-size: 18px; color: #1b2030; }
    </style>
    </head>
    <body>
    <div id="info"></div>
    <script type="module">
    import * as THREE from "three";
    
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xfffdf8);
    const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.set(3, 2.5, 5);
    camera.lookAt(0, 0, 0);
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.4));
    const sun = new THREE.DirectionalLight(0xffffff, 2);
    sun.position.set(3, 5, 4);
    scene.add(sun);
    
    const knot = new THREE.Mesh(
      new THREE.TorusKnotGeometry(0.8, 0.25, 100, 16),
      new THREE.MeshStandardMaterial({ color: 0x2563eb }));
    scene.add(knot);
    
    // an empty box, and a helper that draws it as yellow lines
    const box = new THREE.Box3();
    scene.add(new THREE.Box3Helper(box, 0xe8a000));
    
    const info = document.getElementById("info");
    const clock = new THREE.Clock();
    renderer.setAnimationLoop(function () {
      const dt = clock.getDelta();
      knot.rotation.x += 0.6 * dt;
      knot.rotation.y += 0.9 * dt;
      box.setFromObject(knot);          // fit the box around the knot again
      info.textContent = "min (" + box.min.x.toFixed(1) + ", " + box.min.y.toFixed(1) + ", " + box.min.z.toFixed(1) +
                         ")   max (" + box.max.x.toFixed(1) + ", " + box.max.y.toFixed(1) + ", " + box.max.z.toFixed(1) + ")";
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/box3.html. You should see a turning torus knot inside its Box3.
  3. [Try it]
    1. Replace the knot with a long BoxGeometry(3, 0.3, 0.3).
    2. Watch the numbers: when is the box smallest?
    3. Change the helper colour to red.
Checkpoint: a thin stick inside a box that grows as the stick turns and shrinks when it lines up with an axis.

3. overlap.html Concept 2 · Overlap tests

Week10\overlap.html

  1. Create overlap.html and add this code. Two boxes slide past each other; the overlap test runs every frame.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>Turn Red When Touching</title>
    <style>
      body { margin: 0; overflow: hidden; background: #fffdf8; }
    </style>
    </head>
    <body>
    <script type="module">
    import * as THREE from "three";
    
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xfffdf8);
    const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.set(0, 7, 6);
    camera.lookAt(0, 0, 0);
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.5));
    const sun = new THREE.DirectionalLight(0xffffff, 1.5);
    sun.position.set(3, 5, 4);
    scene.add(sun);
    
    const floor = new THREE.Mesh(new THREE.PlaneGeometry(8, 8),
                                 new THREE.MeshStandardMaterial({ color: 0xe9e2d2 }));
    floor.rotation.x = -Math.PI / 2;
    floor.position.y = -0.5;
    scene.add(floor);
    
    // two cubes, each with its own material so they can change colour separately
    const a = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 0x2563eb }));
    const b = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 0x12854f }));
    scene.add(a, b);
    
    const boxA = new THREE.Box3();
    const boxB = new THREE.Box3();
    const size = new THREE.Vector3(1, 1, 1);    // the size of each cube
    
    const clock = new THREE.Clock();
    renderer.setAnimationLoop(function () {
      const t = clock.getElapsedTime();
      a.position.x = Math.sin(t) * 2.5;          // a slides left and right
      b.position.z = Math.cos(t * 1.3) * 2.5;    // b slides back and forth
    
      boxA.setFromCenterAndSize(a.position, size);
      boxB.setFromCenterAndSize(b.position, size);
    
      const hit = boxA.intersectsBox(boxB);      // do the boxes overlap?
      a.material.color.set(hit ? 0xff3333 : 0x2563eb);
      b.material.color.set(hit ? 0xff3333 : 0x12854f);
    
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/overlap.html. You should see two moving cubes that turn red when they overlap.
  3. [Try it]
    1. Set b.position.y = 1.1: do they still turn red?
    2. Now try 0.9.
    3. Make cube a twice as wide (geometry and size).
Checkpoint: at 1.1 they pass with no hit (a gap in y); at 0.9 they overlap; the wide cube hits more often.

4. slideDemo.html Concept 3 · Walls and sliding

Week10\slideDemo.html

  1. Create slideDemo.html and add this code. Move the cube with the arrow keys or WASD. Hold two keys to push diagonally into a wall.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>Stop at the Wall, Slide Along It</title>
    <style>
      body { margin: 0; overflow: hidden; background: #fffdf8; font-family: Arial, Helvetica, sans-serif; }
      #info { position: absolute; left: 16px; top: 12px; font-size: 20px; color: #1b2030; }
    </style>
    </head>
    <body>
    <div id="info">Arrow keys / WASD: hold two keys and push diagonally into a wall</div>
    <script type="module">
    import * as THREE from "three";
    
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xfffdf8);
    const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.set(0, 12, 8);
    camera.lookAt(0, 0, 0);
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.5));
    const sun = new THREE.DirectionalLight(0xffffff, 1.5);
    sun.position.set(3, 8, 4);
    scene.add(sun);
    
    const floor = new THREE.Mesh(new THREE.PlaneGeometry(14, 10),
                                 new THREE.MeshStandardMaterial({ color: 0xe9e2d2 }));
    floor.rotation.x = -Math.PI / 2;
    scene.add(floor);
    
    // walls: [width, depth, x, z]; each one gets its Box3 once, because walls never move
    const wallMat = new THREE.MeshStandardMaterial({ color: 0x8a94b8 });
    const wallBoxes = [];
    [[10, 1, 0, -3], [1, 6, -4, 1], [4, 1, 2, 2]].forEach(function (w) {
      const wall = new THREE.Mesh(new THREE.BoxGeometry(w[0], 1.4, w[1]), wallMat);
      wall.position.set(w[2], 0.7, w[3]);
      scene.add(wall);
      wallBoxes.push(new THREE.Box3().setFromObject(wall));
    });
    
    const player = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1),
                                  new THREE.MeshStandardMaterial({ color: 0x22d3a6 }));
    player.position.set(0, 0.5, 0);
    scene.add(player);
    const playerBox = new THREE.Box3();
    const size = new THREE.Vector3(1, 1, 1);
    
    function updatePlayerBox() { playerBox.setFromCenterAndSize(player.position, size); }
    function hitsWall(box) {
      return wallBoxes.some(function (w) { return w.intersectsBox(box); });
    }
    
    const keys = {};
    window.addEventListener("keydown", function (e) {
      keys[e.code] = true;
      if (e.code.startsWith("Arrow")) e.preventDefault();
    });
    window.addEventListener("keyup", function (e) { keys[e.code] = false; });
    
    const SPEED = 4;
    const clock = new THREE.Clock();
    renderer.setAnimationLoop(function () {
      const dt = Math.min(clock.getDelta(), 0.05);
      let dx = 0, dz = 0;
      if (keys.ArrowLeft || keys.KeyA) dx -= 1;
      if (keys.ArrowRight || keys.KeyD) dx += 1;
      if (keys.ArrowUp || keys.KeyW) dz -= 1;
      if (keys.ArrowDown || keys.KeyS) dz += 1;
    
      player.position.x += dx * SPEED * dt;                       // try x on its own
      updatePlayerBox();
      if (hitsWall(playerBox)) player.position.x -= dx * SPEED * dt;   // blocked: undo x
    
      player.position.z += dz * SPEED * dt;                       // then try z
      updatePlayerBox();
      if (hitsWall(playerBox)) player.position.z -= dz * SPEED * dt;   // blocked: undo z
    
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/slideDemo.html. You should see the cube stop at walls but keep sliding along them when you move diagonally.
  3. [Try it]
    1. Add a fourth wall to the list.
    2. Change the code to move x and z together, test once, and undo both on a hit.
    3. Push diagonally into a wall, then change it back.
Checkpoint: with one combined test the cube sticks to walls; with separate tests it slides.

5. levelMap.html Concept 4 · Levels from text

Week10\levelMap.html

  1. Create levelMap.html and add this code. Each character is one 2 × 2 tile. tileToWorld turns (column, row) into x and z.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>A Maze from Strings</title>
    <style>
      body { margin: 0; overflow: hidden; background: #fffdf8; }
    </style>
    </head>
    <body>
    <script type="module">
    import * as THREE from "three";
    
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xfffdf8);
    const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.set(0, 14, 9);
    camera.lookAt(0, 0, 0);
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.5));
    const sun = new THREE.DirectionalLight(0xffffff, 1.5);
    sun.position.set(3, 8, 4);
    scene.add(sun);
    
    // the level: # wall, C coin, S spike, P player, . floor
    const MAP = [
      "#######",
      "#P..C.#",
      "#.#.#.#",
      "#C..S.#",
      "#######",
    ];
    const TILE = 2;
    const offsetX = (MAP[0].length - 1) * TILE / 2;   // centre the level on (0, 0)
    const offsetZ = (MAP.length - 1) * TILE / 2;
    
    function tileToWorld(col, row) {
      return new THREE.Vector3(col * TILE - offsetX, 0, row * TILE - offsetZ);
    }
    
    const floor = new THREE.Mesh(new THREE.PlaneGeometry(MAP[0].length * TILE, MAP.length * TILE),
                                 new THREE.MeshStandardMaterial({ color: 0x3c4560 }));
    floor.rotation.x = -Math.PI / 2;
    scene.add(floor);
    
    const wallGeo = new THREE.BoxGeometry(TILE, 1.4, TILE);
    const wallMat = new THREE.MeshStandardMaterial({ color: 0x8a94b8 });
    const coinGeo = new THREE.CylinderGeometry(0.5, 0.5, 0.15, 24);
    coinGeo.rotateX(Math.PI / 2);                      // stand the coin up
    const coinMat = new THREE.MeshStandardMaterial({ color: 0xffcc33, emissive: 0x664400 });
    const spinners = [];                               // coins and spikes spin
    
    // read every character of every row and build what it stands for
    MAP.forEach(function (line, row) {
      for (let col = 0; col < line.length; col++) {
        const ch = line[col];
        const p = tileToWorld(col, row);
        if (ch === "#") {
          const wall = new THREE.Mesh(wallGeo, wallMat);
          wall.position.set(p.x, 0.7, p.z);
          scene.add(wall);
        } else if (ch === "C") {
          const coin = new THREE.Mesh(coinGeo, coinMat);
          coin.position.set(p.x, 1, p.z);
          scene.add(coin);
          spinners.push(coin);
        } else if (ch === "S") {
          const spike = new THREE.Mesh(new THREE.IcosahedronGeometry(0.5),
                                       new THREE.MeshStandardMaterial({ color: 0xcc2222 }));
          spike.position.set(p.x, 0.8, p.z);
          scene.add(spike);
          spinners.push(spike);
        } else if (ch === "P") {
          const player = new THREE.Mesh(new THREE.BoxGeometry(1.2, 1.2, 1.2),
                                        new THREE.MeshStandardMaterial({ color: 0x22d3a6 }));
          player.position.set(p.x, 0.6, p.z);
          scene.add(player);
        }
      }
    });
    
    const clock = new THREE.Clock();
    renderer.setAnimationLoop(function () {
      const dt = clock.getDelta();
      spinners.forEach(function (s) { s.rotation.y += 2 * dt; });
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/levelMap.html. You should see a small level built from six strings.
  3. [Try it]
    1. Add a new row of walls and floor to the MAP (keep every string the same length).
    2. Add two more C coins.
    3. Make walls taller: change 1.4 and 0.7 to 2.4 and 1.2.
Checkpoint: a bigger maze with extra coins, built only by editing the strings.

6. coinCollector.html Objectives 1–8

Week10\coinCollector.html

  1. Create coinCollector.html with this scaffold.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>Coin Collector</title>
    <style>
      body { margin: 0; overflow: hidden; background: #1d2333; font-family: Arial, Helvetica, sans-serif; }
      #hud { position: absolute; top: 10px; left: 12px; color: #ffffff; font-size: 20px; pointer-events: none; text-shadow: 0 1px 3px #000; }
      #msg { position: absolute; top: 35%; left: 0; right: 0; text-align: center; color: #ffffff; font-size: 28px; pointer-events: none; text-shadow: 0 2px 6px #000; }
    </style>
    </head>
    <body>
    <div id="hud">Coins: <span id="coins">0</span> / <span id="total">0</span> &nbsp;&nbsp; Lives: <span id="lives">3</span> &nbsp;&nbsp; Time: <span id="time">0</span></div>
    <div id="msg">Collect every coin, avoid the spikes<br>Arrow keys / WASD to move &middot; B shows the boxes<br>Press Enter to start</div>
    
    <script type="module">
    import * as THREE from "three";
    
    // TODO: the steps below go here
    </script>
    </body>
    </html>
  2. Add the scene, camera, renderer and lights.
    // ---------- scene, camera, renderer ----------
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x1d2333);
    const camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 200);
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.shadowMap.enabled = true;
    document.body.appendChild(renderer.domElement);
    
    scene.add(new THREE.HemisphereLight(0xdde6ff, 0x30384a, 1.2));
    const sun = new THREE.DirectionalLight(0xffffff, 2);
    sun.position.set(8, 20, 10);
    sun.castShadow = true;
    sun.shadow.camera.left = -20; sun.shadow.camera.right = 20;
    sun.shadow.camera.top = 20; sun.shadow.camera.bottom = -20;
    scene.add(sun);
  3. [Obj 7] Add the level map. Every string is a row; tileToWorld() turns a column and row into a 3D position.
    // ---------- the level, drawn as text ----------
    //   # wall   C coin   S spike   P player start   . floor
    const MAP = [
      "###############",
      "#P..#.....#..C#",
      "#.#.#.###.#.#.#",
      "#.#...#C....#.#",
      "#.###.#.#####.#",
      "#C..S.......S.#",
      "###.#####.###.#",
      "#...#C..#...#.#",
      "#.#.#.#.#.#.#C#",
      "#.#...#...#...#",
      "#.#####.#####.#",
      "#C....S.....C.#",
      "###############",
    ];
    const TILE = 2;
    const offsetX = (MAP[0].length - 1) * TILE / 2;   // centre the level on (0, 0)
    const offsetZ = (MAP.length - 1) * TILE / 2;
    function tileToWorld(col, row) {
      return new THREE.Vector3(col * TILE - offsetX, 0, row * TILE - offsetZ);
    }
    
    const floor = new THREE.Mesh(new THREE.PlaneGeometry(MAP[0].length * TILE, MAP.length * TILE),
                                 new THREE.MeshStandardMaterial({ color: 0x3c4560 }));
    floor.rotation.x = -Math.PI / 2;
    floor.receiveShadow = true;
    scene.add(floor);
  4. [Obj 1, 2, 7, 8] Build the level from the map. Each wall gets its Box3 once (walls never move), plus a Box3Helper for debugging.
    // ---------- build walls, coins and spikes from the map ----------
    const wallBoxes = [];     // one Box3 per wall, worked out once
    const coins = [];
    const spikes = [];
    const helpers = [];       // Box3Helpers, shown with the B key
    const start = new THREE.Vector3();
    
    const WALL_H = 1.4;
    const wallGeo = new THREE.BoxGeometry(TILE, WALL_H, TILE);
    const wallMat = new THREE.MeshStandardMaterial({ color: 0x8a94b8 });
    const coinGeo = new THREE.CylinderGeometry(0.5, 0.5, 0.15, 24);
    coinGeo.rotateX(Math.PI / 2);                         // stand the coin up once, in the geometry
    const coinMat = new THREE.MeshStandardMaterial({ color: 0xffcc33, metalness: 0.3, roughness: 0.4, emissive: 0x664400 });
    
    MAP.forEach(function (line, row) {
      for (let col = 0; col < line.length; col++) {
        const ch = line[col];
        const p = tileToWorld(col, row);
        if (ch === "#") {
          const wall = new THREE.Mesh(wallGeo, wallMat);
          wall.position.set(p.x, WALL_H / 2, p.z);
          wall.castShadow = true;
          wall.receiveShadow = true;
          scene.add(wall);
          const box = new THREE.Box3().setFromObject(wall);    // the wall never moves
          wallBoxes.push(box);
          helpers.push(new THREE.Box3Helper(box, 0x22d3a6));
        } else if (ch === "C") {
          const coin = new THREE.Mesh(coinGeo, coinMat);
          coin.position.set(p.x, 1, p.z);
          coin.castShadow = true;
          scene.add(coin);
          coins.push(coin);
        } else if (ch === "S") {
          spikes.push(makeSpike(p));
        } else if (ch === "P") {
          start.copy(p);
        }
      }
    });
  5. [Obj 6] Add makeSpike(): a group of a ball and six cones, with its own box in userData.
    function makeSpike(p) {
      const spike = new THREE.Group();
      const ball = new THREE.Mesh(new THREE.SphereGeometry(0.45, 16, 12),
                                  new THREE.MeshStandardMaterial({ color: 0x881111 }));
      spike.add(ball);
      const coneGeo = new THREE.ConeGeometry(0.18, 0.6, 8);
      const coneMat = new THREE.MeshStandardMaterial({ color: 0xff4444 });
      [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]].forEach(function (d) {
        const cone = new THREE.Mesh(coneGeo, coneMat);
        cone.position.set(d[0] * 0.55, d[1] * 0.55, d[2] * 0.55);
        cone.lookAt(d[0] * 2, d[1] * 2, d[2] * 2);              // point outwards
        cone.rotateX(Math.PI / 2);
        spike.add(cone);
      });
      spike.traverse(function (part) { part.castShadow = true; });
      spike.position.set(p.x, 0.8, p.z);
      spike.userData = { start: p.clone(), dir: 1, speed: 4, box: new THREE.Box3() };
      scene.add(spike);
      return spike;
    }
  6. [Obj 1, 2, 8] Add the player, its box, and the hitsWall() test.
    // ---------- the player ----------
    const PLAYER_SIZE = 1.2;
    const player = new THREE.Mesh(new THREE.BoxGeometry(PLAYER_SIZE, PLAYER_SIZE, PLAYER_SIZE),
                                  new THREE.MeshStandardMaterial({ color: 0x22d3a6 }));
    player.castShadow = true;
    scene.add(player);
    const playerBox = new THREE.Box3();
    const playerSize = new THREE.Vector3(PLAYER_SIZE, PLAYER_SIZE, PLAYER_SIZE);
    const playerHelper = new THREE.Box3Helper(playerBox, 0xffff00);
    helpers.push(playerHelper);
    
    function updatePlayerBox() {
      playerBox.setFromCenterAndSize(player.position, playerSize);
    }
    function hitsWall(box) {
      return wallBoxes.some(function (w) { return w.intersectsBox(box); });
    }
  7. [Obj 8] Add the keyboard. B adds or removes every Box3Helper.
    // ---------- keyboard ----------
    const keys = {};
    window.addEventListener("keydown", function (e) {
      keys[e.code] = true;
      if (e.code.startsWith("Arrow")) e.preventDefault();
      if (e.code === "Enter" && state !== "playing") startGame();
      if (e.code === "KeyB") {                                  // show or hide every box
        const show = !playerHelper.parent;
        helpers.forEach(function (h) { if (show) scene.add(h); else scene.remove(h); });
      }
    });
    window.addEventListener("keyup", function (e) { keys[e.code] = false; });
  8. [Obj 3, 4] Add movePlayer(): move x, test, undo if blocked; then the same for z.
    // ---------- movement: one axis at a time, so we slide along walls ----------
    const SPEED = 6;
    function movePlayer(dt) {
      let dx = 0, dz = 0;
      if (keys.ArrowLeft || keys.KeyA) dx -= 1;
      if (keys.ArrowRight || keys.KeyD) dx += 1;
      if (keys.ArrowUp || keys.KeyW) dz -= 1;
      if (keys.ArrowDown || keys.KeyS) dz += 1;
    
      player.position.x += dx * SPEED * dt;     // try x
      updatePlayerBox();
      if (hitsWall(playerBox)) player.position.x -= dx * SPEED * dt;   // blocked: undo x
    
      player.position.z += dz * SPEED * dt;     // then try z
      updatePlayerBox();
      if (hitsWall(playerBox)) player.position.z -= dz * SPEED * dt;   // blocked: undo z
    
      updatePlayerBox();
    }
  9. [Obj 3, 5] Add updateCoins(). It loops backwards because it removes coins from the array.
    // ---------- coins ----------
    const coinBox = new THREE.Box3();
    function updateCoins(dt) {
      for (let i = coins.length - 1; i >= 0; i--) {             // backwards, because we remove
        const coin = coins[i];
        coin.rotation.y += 3 * dt;                               // spin
        coinBox.setFromObject(coin);
        if (coinBox.intersectsBox(playerBox)) {
          scene.remove(coin);
          coins.splice(i, 1);
          collected++;
          coinsEl.textContent = collected;
          if (coins.length === 0) endGame("All coins in " + elapsed.toFixed(1) + " s!");
        }
      }
    }
  10. [Obj 3, 6] Add updateSpikes(): patrol, bounce off walls, and hurt the player unless they are invulnerable.
    // ---------- spikes patrol left and right, turning at walls ----------
    let invulnerable = 0;     // seconds of safety after being hit
    function updateSpikes(dt) {
      spikes.forEach(function (s) {
        const u = s.userData;
        s.position.x += u.dir * u.speed * dt;
        s.rotation.y += 4 * dt;
        u.box.setFromCenterAndSize(s.position, new THREE.Vector3(1, 1, 1));
        if (hitsWall(u.box)) {                                   // bounce off the wall
          s.position.x -= u.dir * u.speed * dt;
          u.dir = -u.dir;
        }
        if (invulnerable <= 0 && u.box.intersectsBox(playerBox)) {
          lives--;
          livesEl.textContent = lives;
          invulnerable = 1.5;
          u.dir = -u.dir;                                        // the spike bounces back too
          if (lives <= 0) endGame("Out of lives! " + collected + " coins.");
        }
      });
      invulnerable -= dt;
      player.visible = invulnerable <= 0 || Math.floor(invulnerable * 10) % 2 === 0;   // blink
    }
  11. [Obj 5, 6] Add the game state, then the animation loop with the follow camera and the resize handler.
    // ---------- game state ----------
    let state = "ready";
    let collected = 0;
    let lives = 3;
    let elapsed = 0;
    const totalCoins = coins.length;
    const coinsEl = document.getElementById("coins");
    const livesEl = document.getElementById("lives");
    const timeEl = document.getElementById("time");
    const msgEl = document.getElementById("msg");
    document.getElementById("total").textContent = totalCoins;
    
    function startGame() {
      if (state === "over") { location.reload(); return; }   // simplest full reset
      state = "playing";
      msgEl.innerHTML = "";
    }
    function endGame(text) {
      state = "over";
      msgEl.innerHTML = text + "<br>Press Enter to play again";
    }
    
    // ---------- animation loop ----------
    player.position.set(start.x, PLAYER_SIZE / 2, start.z);
    updatePlayerBox();
    const clock = new THREE.Clock();
    renderer.setAnimationLoop(function () {
      const dt = Math.min(clock.getDelta(), 0.05);
      if (state === "playing") {
        movePlayer(dt);
        updateSpikes(dt);
        updateCoins(dt);
        elapsed += dt;
        timeEl.textContent = elapsed.toFixed(0);
      }
      // the camera follows from above and behind
      camera.position.lerp(new THREE.Vector3(player.position.x, 18, player.position.z + 8), 1 - Math.exp(-3 * dt));
      camera.lookAt(player.position);
      renderer.render(scene, camera);
    });
    
    window.addEventListener("resize", function () {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    });
    camera.position.set(start.x, 18, start.z + 8);
  12. Save, press Enter, collect the coins and press B to see the boxes.
Checkpoint: walls block and slide, coins are collected, spikes patrol and cost lives, and B shows the boxes (Objectives 1-8).

Marking rubric

CriterionPointsScore
Level built from a text map2
Walls with Box3; player blocked and sliding4
Coins collected and removed correctly3
Spikes patrol, cost lives, invulnerability3
Box3Helper debug view2
Runs with no console errors1
Total15

Common errors

Progress and quiz scores are also tracked on the Week 10 lab page in the class website.