Week 10 — 3D Collision Detection

Games are full of things that touch: walls that block, coins you pick up, spikes that hurt. This week you wrap objects in Box3 bounding boxes, test overlaps with intersectsBox, stop the player at walls while still sliding along them, and build a whole level from a few lines of text — for Coin Collector, a maze where you grab every coin while dodging patrolling spikes.

🎯 Objectives

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

🛠 Weekly tasks

  1. Objective 1 — describe objects with bounding boxes: Activity 1 + build coinCollector.html.
  2. Objective 2 — build boxes from objects and sizes: Activity 2 + build coinCollector.html.
  3. Objective 3 — test overlaps with intersectsBox: Activity 3 + build coinCollector.html.
  4. Objective 4 — block the player at walls and slide: Activity 4 + build coinCollector.html.
  5. Objective 5 — collect coins and update the score: Activity 5 + build coinCollector.html.
  6. Objective 6 — add patrolling spikes and lives: Activity 6 + build coinCollector.html.
  7. Objective 7 — build the maze from a text map: Activity 7 + build coinCollector.html.
  8. Objective 8 — show the boxes with Box3Helper: Activity 8 + build coinCollector.html.
  9. Examples — build the lecture examples box3.html, overlap.html, slideDemo.html, levelMap.html, one file per concept, and try each change. (Concepts 1–4)
  10. Build your own coinCollector_yourname.html — design your own level, add a key and a locked door, and save the best time. (All objectives)

🎓 Lecture activity Open lecture slides →

A 90-minute session of 35 slides. Each concept is taught four ways: the big idea, a short example with its live 3D output, a line-by-line explanation, and a 5-minute “try it” task. The lab work at 1:00 uses the Lab activity below.

Session plan

  1. 0:0010 minWarm-upReview questions on last week
  2. 0:1010 minGame & objectivesThis week’s game, objectives and key words
  3. 0:2035 minConceptsBig idea → code with live 3D output → line by line → try it
  4. 0:555 minCheck understandingCommon mistakes and a 4-question quiz
  5. 1:0025 minLabBuild the files in the Lab activity below
  6. 1:255 minWrap-upBuild-your-own task, marking guide and recap

Concepts this week

  • 1. Bounding boxes — Box3: the smallest box around an object
  • 2. Overlap tests — intersectsBox, containsPoint
  • 3. Walls and sliding — Move one axis, test, undo if blocked
  • 4. Levels from text — An array of strings becomes a 3D maze

The slides open as a page on this site. Press F for full screen, the arrow keys to move, N for speaker notes, and P to save as PDF (turn on “Background graphics”).

🧪 Lab activity: work through the files Printable lab sheet

Set up your Week10 npm project (step 1). Build Coin Collector below, writing the code shown for each step, all in one file, coinCollector.html. Start with the four example files from the lecture (one per concept), then build the game.

3D files run through Vite. Each week is an npm project: Three.js is installed with npm install three, and the Vite dev server (npx vite) serves your files at http://localhost:5173/ and reloads them when you save. Opening an HTML file by double-clicking shows a blank page. New to Node.js? Week 7’s first step and the Setup guide show the installation.
  1. Set up your Week10 project npm · Vite

    Week10\ — a new npm project, once at the start of the week.

    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
  2. box3.html Concept 1 · Bounding boxes

    Week10\box3.html — Box3: the smallest box around an object.

    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.
  3. overlap.html Concept 2 · Overlap tests

    Week10\overlap.html — intersectsBox, containsPoint.

    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).
  4. slideDemo.html Concept 3 · Walls and sliding

    Week10\slideDemo.html — Move one axis, test, undo if blocked.

    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.
  5. levelMap.html Concept 4 · Levels from text

    Week10\levelMap.html — An array of strings becomes a 3D maze.

    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.
  6. coinCollector.html Objectives 1–8

    Week10\coinCollector.html — the maze game.

    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.
Finished example output — click the game first so it receives your key presses

Click the game, press Enter, then move with the arrow keys or WASD. Press B at any time to see the bounding boxes.

📚 Distance or boxes?