Week 14 Lab Sheet — Final Project: Endless Runner

Web Games Development · Endless runner & final project · ~150 minutes

Objectives

  1. Organise a game with states (menu, playing, paused, over) and one update function per state.
  2. Move between lanes smoothly, jump with gravity and slide with a smaller collision box.
  3. Spawn rows of obstacles and coins with a timer, always leaving a way through.
  4. Reuse objects with an object pool (a class with get() and release()).
  5. Move the world towards the player and scroll a texture with offset.
  6. Design a difficulty curve: speed and spawn rate increase over time, up to a limit.
  7. Add atmosphere with Fog and keep a best score with localStorage.
  8. Plan, build and present your own 3D game as the final project.

Instructions

Set up a Week14 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 Week14 project npm · Vite

Week14\

  1. Create a folder named Week14, 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/statesDemo.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. statesDemo.html Concept 1 · Game states

Week14\statesDemo.html

  1. Create statesDemo.html and add this code. Press Enter to start, P to pause and carry on, X to crash. Only the current state’s update runs.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>One Update per State</title>
    <style>
      body { margin: 0; overflow: hidden; background: #fffdf8; font-family: monospace; }
      #label { position: absolute; left: 0; right: 0; top: 16px; text-align: center; font-size: 30px; font-weight: bold; color: #a84c14; }
      #help { position: absolute; left: 0; right: 0; bottom: 16px; text-align: center; font-size: 18px; color: #1b2030; }
    </style>
    </head>
    <body>
    <div id="label"></div>
    <div id="help">Enter: start &middot; P: pause / carry on &middot; X: crash</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, 2.5, 6);
    camera.lookAt(0, 0.8, 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, 0x4a7a3a, 1.6));
    
    const runner = new THREE.Mesh(new THREE.CapsuleGeometry(0.4, 0.8, 8, 16),
                                  new THREE.MeshStandardMaterial({ color: 0xe8823a }));
    runner.position.y = 0.8;
    scene.add(runner);
    const floor = new THREE.Mesh(new THREE.PlaneGeometry(8, 8),
                                 new THREE.MeshStandardMaterial({ color: 0x555a63 }));
    floor.rotation.x = -Math.PI / 2;
    scene.add(floor);
    
    let state = "menu";        // "menu", "playing", "paused" or "over"
    const label = document.getElementById("label");
    
    // keys change the state, but only from the right states
    window.addEventListener("keydown", function (e) {
      if (e.code === "Enter" && (state === "menu" || state === "over")) {
        runner.rotation.x = 0;
        state = "playing";
      } else if (e.code === "KeyP" && (state === "playing" || state === "paused")) {
        state = state === "playing" ? "paused" : "playing";
      } else if (e.code === "KeyX" && state === "playing") {
        state = "over";
      }
    });
    
    // one update function for each state
    function updateMenu(t) {
      runner.position.y = 0.8 + Math.abs(Math.sin(t * 4)) * 0.3;     // jog on the spot
    }
    function updatePlaying(t) {
      runner.position.y = 0.8 + Math.abs(Math.sin(t * 9)) * 0.15;    // run
      runner.position.x = Math.sin(t * 2) * 1.5;                      // weave left and right
    }
    function updateOver(dt) {
      runner.rotation.x = Math.max(-Math.PI / 2, runner.rotation.x - 4 * dt);   // fall flat
    }
    
    const clock = new THREE.Clock();
    renderer.setAnimationLoop(function () {
      const dt = Math.min(clock.getDelta(), 0.05);
      const t = clock.elapsedTime;
      if (state === "playing") updatePlaying(t);
      else if (state === "menu") updateMenu(t);
      else if (state === "over") updateOver(dt);
      // "paused": no update, so nothing moves, but we still draw
      label.textContent = 'state = "' + state + '"';
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/statesDemo.html. You should see the label change state as you press the keys, and the runner behave differently in each state.
  3. [Try it]
    1. Add a "ready" state after Enter that lasts 3 seconds, then switches to "playing".
    2. Show 3, 2, 1 in the label during "ready".
    3. Make R go from "over" back to "menu".
Checkpoint: a 3-2-1 countdown before running, and R returning to the menu after a crash.

3. lanesDemo.html Concept 2 · Lanes, jump, slide

Week14\lanesDemo.html

  1. Create lanesDemo.html and add this code. Change lane with Left / Right, jump with Up or Space, slide with Down.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>Glide, Jump and Slide</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">Left / Right: change lane &middot; Up or Space: jump &middot; Down: slide</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(50, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.set(0, 4, 7);
    camera.lookAt(0, 0.8, -2);
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    scene.add(new THREE.HemisphereLight(0xffffff, 0x4a7a3a, 1.6));
    
    // a road with two lane lines
    const road = new THREE.Mesh(new THREE.PlaneGeometry(9, 20),
                                new THREE.MeshStandardMaterial({ color: 0x555a63 }));
    road.rotation.x = -Math.PI / 2;
    road.position.z = -5;
    scene.add(road);
    [-1.25, 1.25].forEach(function (x) {
      const line = new THREE.Mesh(new THREE.PlaneGeometry(0.08, 20), new THREE.MeshBasicMaterial({ color: 0xffffff }));
      line.rotation.x = -Math.PI / 2;
      line.position.set(x, 0.01, -5);
      scene.add(line);
    });
    
    const player = new THREE.Group();
    const body = new THREE.Mesh(new THREE.CapsuleGeometry(0.4, 0.8, 8, 16),
                                new THREE.MeshStandardMaterial({ color: 0xe8823a }));
    body.position.y = 0.8;
    player.add(body);
    scene.add(player);
    
    const LANES = [-2.5, 0, 2.5];
    const GRAVITY = 25;
    const JUMP_SPEED = 9;
    let lane = 1;          // 0 = left, 1 = middle, 2 = right
    let vy = 0;
    let slideTime = 0;
    
    window.addEventListener("keydown", function (e) {
      if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Space"].includes(e.code)) e.preventDefault();
      if (e.repeat) return;                                       // ignore auto-repeat
      if (e.code === "ArrowLeft" || e.code === "KeyA") lane = Math.max(0, lane - 1);
      if (e.code === "ArrowRight" || e.code === "KeyD") lane = Math.min(2, lane + 1);
      if ((e.code === "ArrowUp" || e.code === "KeyW" || e.code === "Space") && player.position.y === 0) {
        vy = JUMP_SPEED;                                          // only jump from the ground
      }
      if (e.code === "ArrowDown" || e.code === "KeyS") slideTime = 0.7;
    });
    
    const clock = new THREE.Clock();
    renderer.setAnimationLoop(function () {
      const dt = Math.min(clock.getDelta(), 0.05);
      player.position.x += (LANES[lane] - player.position.x) * Math.min(1, 12 * dt);   // glide to the lane
      vy -= GRAVITY * dt;                                                              // gravity
      player.position.y = Math.max(0, player.position.y + vy * dt);
      if (player.position.y === 0) vy = 0;                                             // landed
      slideTime -= dt;
      player.scale.y = slideTime > 0 ? 0.5 : 1;                                        // squash to slide
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/lanesDemo.html. You should see the runner glide between three lanes, jump and land, and squash down to slide.
  3. [Try it]
    1. Add a double jump: allow a second jump in mid-air (count jumps, reset on landing).
    2. Make the glide slower: change 12 to 4.
    3. Add a fourth and fifth lane.
Checkpoint: a second, mid-air jump, a lazier lane change, and a wider road of five lanes.

4. poolDemo.html Concept 3 · Object pools

Week14\poolDemo.html

  1. Create poolDemo.html and add this code. The counter shows how few objects are ever made, however long it runs.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>An Object Pool</title>
    <style>
      body { margin: 0; overflow: hidden; background: #fffdf8; font-family: monospace; }
      #info { position: absolute; left: 16px; top: 12px; font-size: 22px; color: #1b2030; white-space: pre; }
    </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);
    scene.fog = new THREE.Fog(0xfffdf8, 15, 40);
    const camera = new THREE.PerspectiveCamera(55, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.set(0, 4, 7);
    camera.lookAt(0, 0.5, -6);
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    scene.add(new THREE.HemisphereLight(0xffffff, 0x4a7a3a, 1.6));
    
    const road = new THREE.Mesh(new THREE.PlaneGeometry(9, 80),
                                new THREE.MeshStandardMaterial({ color: 0x555a63 }));
    road.rotation.x = -Math.PI / 2;
    road.position.z = -30;
    scene.add(road);
    
    // the pool: reuse hidden objects instead of making new ones
    class Pool {
      constructor(create) {
        this.create = create;    // a function that makes one new object
        this.free = [];          // hidden, ready to reuse
        this.active = [];        // in play
      }
      get() {
        const obj = this.free.pop() || this.create();
        obj.visible = true;
        this.active.push(obj);
        return obj;
      }
      release(obj) {
        obj.visible = false;
        this.active.splice(this.active.indexOf(obj), 1);
        this.free.push(obj);
      }
    }
    
    let made = 0;       // how many objects were ever created
    let spawned = 0;    // how many times one was put into play
    const colours = [0xd9534f, 0xf0ad4e, 0x6c757d];
    const pool = new Pool(function () {
      made++;
      const box = new THREE.Mesh(new THREE.BoxGeometry(1.6, 1, 0.6),
                                 new THREE.MeshStandardMaterial({ color: colours[made % 3] }));
      scene.add(box);
      return box;
    });
    
    const info = document.getElementById("info");
    let timer = 0;
    const clock = new THREE.Clock();
    renderer.setAnimationLoop(function () {
      const dt = Math.min(clock.getDelta(), 0.05);
    
      timer -= dt;
      if (timer <= 0) {                                    // spawn one in a random lane
        timer = 0.35;
        const obj = pool.get();
        spawned++;
        obj.position.set([-2.5, 0, 2.5][Math.floor(Math.random() * 3)], 0.5, -40);
      }
    
      for (let i = pool.active.length - 1; i >= 0; i--) {  // move everything towards us
        const obj = pool.active[i];
        obj.position.z += 14 * dt;
        if (obj.position.z > 6) pool.release(obj);         // passed the camera: back to the pool
      }
    
      info.textContent = "spawned: " + spawned + "\nmade:    " + made +
                         "\nactive:  " + pool.active.length + "   free: " + pool.free.length;
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/poolDemo.html. You should see objects streaming past; “made” stops growing.
  3. [Try it]
    1. Spawn twice as often (0.35 → 0.15): how high does “made” go?
    2. Remove the pool.release(obj) line: what happens to “made”?
    3. Put it back and add a second pool for small yellow coins.
Checkpoint: “made” stops at a few dozen with the pool; without release it grows forever.

5. difficultyDemo.html Concept 4 · Difficulty and atmosphere

Week14\difficultyDemo.html

  1. Create difficultyDemo.html and add this code. The speed climbs to the limit, then the demo resets. Watch the posts appear out of the fog.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>Faster and Faster, Inside the Fog</title>
    <style>
      body { margin: 0; overflow: hidden; background: #87ceeb; font-family: monospace; }
      #info { position: absolute; left: 16px; top: 12px; font-size: 22px; font-weight: bold; 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(0x87ceeb);
    scene.fog = new THREE.Fog(0x87ceeb, 15, 45);     // clear up to 15 units, fully fogged at 45
    const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 100);
    camera.position.set(0, 3, 6);
    camera.lookAt(0, 1, -10);
    const renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    scene.add(new THREE.HemisphereLight(0xffffff, 0x4a7a3a, 1.6));
    
    const road = new THREE.Mesh(new THREE.PlaneGeometry(9, 100),
                                new THREE.MeshStandardMaterial({ color: 0x555a63 }));
    road.rotation.x = -Math.PI / 2;
    road.position.z = -40;
    scene.add(road);
    const grass = new THREE.Mesh(new THREE.PlaneGeometry(100, 100),
                                 new THREE.MeshStandardMaterial({ color: 0x5fa04e }));
    grass.rotation.x = -Math.PI / 2;
    grass.position.set(0, -0.01, -40);
    scene.add(grass);
    
    // white posts along both sides of the road
    const posts = [];
    for (let i = 0; i < 24; i++) {
      const post = new THREE.Mesh(new THREE.BoxGeometry(0.4, 2, 0.4),
                                  new THREE.MeshStandardMaterial({ color: 0xffffff }));
      post.position.set(i % 2 ? 5 : -5, 1, -i * 4);
      scene.add(post);
      posts.push(post);
    }
    
    const MAX_SPEED = 32;
    const TIME_SCALE = 4;     // demo only: run the clock 4 times faster to see the whole curve
    let elapsed = 0;
    const info = document.getElementById("info");
    const clock = new THREE.Clock();
    
    renderer.setAnimationLoop(function () {
      const dt = Math.min(clock.getDelta(), 0.05);
      elapsed += dt * TIME_SCALE;
      if (elapsed > 70) elapsed = 0;                            // start the curve again
    
      const speed = Math.min(MAX_SPEED, 12 + elapsed * 0.35);  // the difficulty curve
      posts.forEach(function (post) {
        post.position.z += speed * dt;
        if (post.position.z > 6) post.position.z -= 96;         // back to the far end, inside the fog
      });
    
      info.textContent = "time " + elapsed.toFixed(0) + " s   speed " + speed.toFixed(1) +
                         (speed === MAX_SPEED ? "  (MAX)" : "");
      renderer.render(scene, camera);
    });
    </script>
    </body>
    </html>
  2. Save. With npx vite running, open http://localhost:5173/difficultyDemo.html. You should see speed rising to its limit; posts emerging from fog.
  3. [Try it]
    1. Change TIME_SCALE to 1 (real time).
    2. Change the curve to start at 8 and climb by 0.6 per second.
    3. Move the fog closer: Fog(…, 8, 25).
Checkpoint: a slower real-time ramp, a different curve, and posts appearing much later out of thick fog.

6. laneRunner.html Objectives 1–7

Week14\laneRunner.html

  1. Create laneRunner.html with this scaffold. The HUD shows score, coins and the best score.
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    <title>Lane Runner</title>
    <style>
      body { margin: 0; overflow: hidden; background: #87ceeb; font-family: Arial, Helvetica, sans-serif; user-select: none; }
      #hud { position: absolute; top: 10px; left: 12px; right: 12px; display: flex; justify-content: space-between; color: #ffffff; font-size: 22px; pointer-events: none; text-shadow: 0 1px 3px #000; }
      #msg { position: absolute; top: 22%; left: 0; right: 0; text-align: center; color: #ffffff; font-size: 24px; line-height: 1.6; pointer-events: none; text-shadow: 0 2px 6px #000; }
      #msg h1 { font-size: 56px; margin: 0 0 10px; letter-spacing: 3px; }
    </style>
    </head>
    <body>
    <div id="hud">
      <div>Score: <span id="score">0</span></div>
      <div>Coins: <span id="coins">0</span></div>
      <div>Best: <span id="best">0</span></div>
    </div>
    <div id="msg"></div>
    
    <script type="module">
    import * as THREE from "three";
    
    // TODO: the steps below go here
    </script>
    </body>
    </html>
  2. [Obj 7] Add the scene with fog, the camera behind the runner, and the lights.
    // ---------- scene, camera, renderer, fog ----------
    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0x87ceeb);
    scene.fog = new THREE.Fog(0x87ceeb, 25, 75);       // far things fade into the sky
    const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 200);
    camera.position.set(0, 4.5, 8);
    camera.lookAt(0, 1, -6);
    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(0xffffff, 0x4a7a3a, 1.3));
    const sun = new THREE.DirectionalLight(0xffffff, 2);
    sun.position.set(5, 12, 6);
    sun.castShadow = true;
    sun.shadow.camera.left = -10; sun.shadow.camera.right = 10;
    sun.shadow.camera.top = 10; sun.shadow.camera.bottom = -30;
    scene.add(sun);
  3. [Obj 5] Add the road: a canvas texture with lane lines, repeated 20 times along the road, and the grass.
    // ---------- the road: a canvas texture that scrolls ----------
    function roadTexture() {
      const c = document.createElement("canvas");
      c.width = 256;
      c.height = 256;
      const ctx = c.getContext("2d");
      ctx.fillStyle = "#555a63";
      ctx.fillRect(0, 0, 256, 256);
      ctx.fillStyle = "#ffffff";
      [85, 171].forEach(function (x) { ctx.fillRect(x - 3, 0, 6, 128); });   // dashed lane lines
      ctx.fillRect(0, 0, 8, 256);                                             // solid edges
      ctx.fillRect(248, 0, 8, 256);
      const tex = new THREE.CanvasTexture(c);
      tex.colorSpace = THREE.SRGBColorSpace;
      tex.wrapT = THREE.RepeatWrapping;
      tex.repeat.set(1, 20);
      return tex;
    }
    const roadTex = roadTexture();
    const road = new THREE.Mesh(new THREE.PlaneGeometry(9, 200), new THREE.MeshStandardMaterial({ map: roadTex }));
    road.rotation.x = -Math.PI / 2;
    road.position.z = -90;
    road.receiveShadow = true;
    scene.add(road);
    const grass = new THREE.Mesh(new THREE.PlaneGeometry(200, 200), new THREE.MeshStandardMaterial({ color: 0x5fa04e }));
    grass.rotation.x = -Math.PI / 2;
    grass.position.set(0, -0.01, -90);
    scene.add(grass);
  4. [Obj 2] Add the player, updatePlayer() (lanes, gravity, sliding) and the collision box that shrinks while sliding.
    // ---------- the player: three lanes, jump and slide ----------
    const LANES = [-2.5, 0, 2.5];
    const player = new THREE.Group();
    const skin = new THREE.MeshStandardMaterial({ color: 0xe8823a });
    const body = new THREE.Mesh(new THREE.CapsuleGeometry(0.4, 0.8, 8, 16), skin);
    body.position.y = 0.8;
    const head = new THREE.Mesh(new THREE.SphereGeometry(0.32, 16, 12), new THREE.MeshStandardMaterial({ color: 0xffd7b5 }));
    head.position.y = 1.65;
    player.add(body, head);
    player.traverse(function (p) { p.castShadow = true; });
    scene.add(player);
    
    const GRAVITY = 25;
    const JUMP_SPEED = 9;
    let lane = 1;           // 0 = left, 1 = middle, 2 = right
    let vy = 0;             // vertical speed for jumping
    let slideTime = 0;      // > 0 while sliding
    
    function updatePlayer(dt) {
      player.position.x += (LANES[lane] - player.position.x) * Math.min(1, 12 * dt);   // glide to the lane
      vy -= GRAVITY * dt;
      player.position.y = Math.max(0, player.position.y + vy * dt);
      if (player.position.y === 0) vy = 0;
      slideTime -= dt;
      player.scale.y = slideTime > 0 ? 0.5 : 1;                  // squash down to slide
    }
    
    // The player's collision box shrinks while sliding
    const playerBox = new THREE.Box3();
    function updatePlayerBox() {
      const h = slideTime > 0 ? 0.9 : 1.9;
      playerBox.setFromCenterAndSize(
        new THREE.Vector3(player.position.x, player.position.y + h / 2, 0),
        new THREE.Vector3(0.8, h, 0.6));
    }
  5. [Obj 4] Add the Pool class and one pool for each kind of object.
    // ---------- object pools: reuse objects instead of making new ones ----------
    class Pool {
      constructor(create) {
        this.create = create;    // a function that makes one new object
        this.free = [];          // hidden objects waiting to be reused
        this.active = [];        // objects in play
      }
      get() {
        const obj = this.free.pop() || this.create();
        obj.visible = true;
        this.active.push(obj);
        return obj;
      }
      release(obj) {
        obj.visible = false;
        this.active.splice(this.active.indexOf(obj), 1);
        this.free.push(obj);
      }
    }
    
    function addToScene(obj) {
      obj.traverse(function (p) { p.castShadow = true; });
      scene.add(obj);
      return obj;
    }
    const pools = {
      low: new Pool(function () {            // jump over it
        const m = new THREE.Mesh(new THREE.BoxGeometry(2, 0.8, 0.6), new THREE.MeshStandardMaterial({ color: 0xd9534f }));
        m.position.y = 0.4;
        m.userData = { centreY: 0.4, size: new THREE.Vector3(2, 0.8, 0.6) };
        return addToScene(m);
      }),
      high: new Pool(function () {           // slide under it
        const g = new THREE.Group();
        const bar = new THREE.Mesh(new THREE.BoxGeometry(2.2, 0.4, 0.4), new THREE.MeshStandardMaterial({ color: 0xf0ad4e }));
        bar.position.y = 1.6;
        const postMat = new THREE.MeshStandardMaterial({ color: 0x444444 });
        [-1.05, 1.05].forEach(function (x) {
          const post = new THREE.Mesh(new THREE.BoxGeometry(0.15, 1.8, 0.15), postMat);
          post.position.set(x, 0.9, 0);
          g.add(post);
        });
        g.add(bar);
        g.userData = { centreY: 1.6, size: new THREE.Vector3(2, 0.4, 0.4) };
        return addToScene(g);
      }),
      wall: new Pool(function () {           // change lane
        const m = new THREE.Mesh(new THREE.BoxGeometry(2, 2.5, 0.6), new THREE.MeshStandardMaterial({ color: 0x6c757d }));
        m.position.y = 1.25;
        m.userData = { centreY: 1.25, size: new THREE.Vector3(2, 2.5, 0.6) };
        return addToScene(m);
      }),
      coin: new Pool(function () {
        const geo = new THREE.CylinderGeometry(0.35, 0.35, 0.1, 20);
        geo.rotateX(Math.PI / 2);
        const m = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: 0xffcc33, emissive: 0x664400 }));
        m.position.y = 1;
        return addToScene(m);
      }),
      tree: new Pool(function () {
        const g = new THREE.Group();
        const trunk = new THREE.Mesh(new THREE.CylinderGeometry(0.2, 0.25, 1.2, 8), new THREE.MeshStandardMaterial({ color: 0x8b5a2b }));
        trunk.position.y = 0.6;
        const top = new THREE.Mesh(new THREE.ConeGeometry(1.1, 2.6, 10), new THREE.MeshStandardMaterial({ color: 0x2e7d32 }));
        top.position.y = 2.4;
        g.add(trunk, top);
        return addToScene(g);
      }),
    };
    const OBSTACLES = ["low", "high", "wall"];
  6. [Obj 3] Add spawnRow() (one or two blocked lanes, coins in a free lane) and spawnTrees().
    // ---------- spawning rows of obstacles and coins ----------
    const SPAWN_Z = -80;
    function spawnRow() {
      const blocked = Math.random() < 0.35 ? 2 : 1;             // 1 or 2 lanes get an obstacle
      const lanes = [0, 1, 2].sort(function () { return Math.random() - 0.5; });
      for (let i = 0; i < 3; i++) {
        const x = LANES[lanes[i]];
        if (i < blocked) {
          const type = OBSTACLES[Math.floor(Math.random() * OBSTACLES.length)];
          const o = pools[type].get();
          o.position.x = x;
          o.position.z = SPAWN_Z;
        } else if (Math.random() < 0.5) {                        // coins in a free lane
          for (let k = 0; k < 5; k++) {
            const c = pools.coin.get();
            c.position.set(x, 1, SPAWN_Z - k * 2);
          }
        }
      }
    }
    function spawnTrees() {
      [-1, 1].forEach(function (side) {
        const t = pools.tree.get();
        t.position.set(side * (6 + Math.random() * 4), 0, SPAWN_Z - Math.random() * 10);
      });
    }
  7. [Obj 4, 5] Add moveWorld(): scroll the road texture, move every active object, and release what has passed the camera.
    // ---------- moving the world towards the player ----------
    function moveWorld(dt) {
      roadTex.offset.y += speed * dt / 10;                        // one road tile is 10 units long
      Object.keys(pools).forEach(function (name) {
        const pool = pools[name];
        for (let i = pool.active.length - 1; i >= 0; i--) {
          const obj = pool.active[i];
          obj.position.z += speed * dt;
          if (name === "coin") obj.rotation.y += 4 * dt;
          if (obj.position.z > 6) pool.release(obj);              // behind the camera: reuse later
        }
      });
    }
  8. [Obj 2] Add checkCollisions(): crash into obstacles, collect coins.
    // ---------- collisions: crash into obstacles, collect coins ----------
    const obstacleBox = new THREE.Box3();
    function checkCollisions() {
      updatePlayerBox();
      for (const type of OBSTACLES) {
        for (const o of pools[type].active) {
          const centre = new THREE.Vector3(o.position.x, o.userData.centreY, o.position.z);
          obstacleBox.setFromCenterAndSize(centre, o.userData.size);
          if (obstacleBox.intersectsBox(playerBox)) { crash(); return; }
        }
      }
      const coins = pools.coin.active;
      for (let i = coins.length - 1; i >= 0; i--) {
        const c = coins[i];
        if (Math.abs(c.position.x - player.position.x) < 0.8 && Math.abs(c.position.z) < 0.8 &&
            Math.abs(c.position.y - (player.position.y + 1)) < 1.2) {
          pools.coin.release(c);
          coinCount++;
          beep(1200, 0.1, "triangle", 0.25);
        }
      }
    }
  9. Add the sound effects (the same code as Week 13).
    // ---------- sound effects (from Week 13) ----------
    let audio = null;
    function initAudio() {
      if (!audio) audio = new AudioContext();
      if (audio.state === "suspended") audio.resume();
    }
    function beep(freq, duration, type, volume) {
      if (!audio) return;
      const osc = audio.createOscillator();
      const gain = audio.createGain();
      osc.type = type;
      osc.frequency.value = freq;
      gain.gain.setValueAtTime(volume, audio.currentTime);
      gain.gain.exponentialRampToValueAtTime(0.001, audio.currentTime + duration);
      osc.connect(gain).connect(audio.destination);
      osc.start();
      osc.stop(audio.currentTime + duration);
    }
  10. [Obj 1, 7] Add the game states: showMenu(), startGame() (which releases everything back to the pools) and crash(), which saves the best score.
    // ---------- game states: menu, playing, paused, over ----------
    let state = "menu";
    let speed = 0;
    let elapsed = 0;
    let distance = 0;
    let coinCount = 0;
    let spawnTimer = 0;
    let treeTimer = 0;
    let best = Number(localStorage.getItem("laneRunnerBest")) || 0;
    const MAX_SPEED = 32;
    
    const scoreEl = document.getElementById("score");
    const coinsEl = document.getElementById("coins");
    const bestEl = document.getElementById("best");
    const msgEl = document.getElementById("msg");
    bestEl.textContent = best;
    
    function score() { return Math.floor(distance) + coinCount * 10; }
    
    function showMenu() {
      state = "menu";
      msgEl.innerHTML = "<h1>LANE RUNNER</h1>Left / Right or A / D: change lane<br>Up, W or Space: jump &middot; Down or S: slide<br>P: pause<br><br>Press Enter to run";
    }
    
    function startGame() {
      Object.keys(pools).forEach(function (name) {
        const pool = pools[name];
        while (pool.active.length) pool.release(pool.active[0]);
      });
      lane = 1;
      vy = 0;
      slideTime = 0;
      player.position.set(0, 0, 0);
      player.rotation.x = 0;
      elapsed = 0;
      distance = 0;
      coinCount = 0;
      spawnTimer = 1;
      speed = 12;
      msgEl.innerHTML = "";
      state = "playing";
    }
    
    function crash() {
      state = "over";
      beep(110, 0.5, "sawtooth", 0.3);
      if (score() > best) {
        best = score();
        localStorage.setItem("laneRunnerBest", best);
        bestEl.textContent = best;
      }
      msgEl.innerHTML = "<h1>CRASH!</h1>Score " + score() + " &middot; Best " + best + "<br><br>Press Enter to run again";
    }
  11. [Obj 1, 2] Add the keyboard. e.repeat is ignored so a held key does not jump twice.
    // ---------- keyboard ----------
    window.addEventListener("keydown", function (e) {
      if (["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown", "Space"].includes(e.code)) e.preventDefault();
      if (e.repeat) return;                                       // ignore auto-repeat
      initAudio();
      if (e.code === "Enter" && (state === "menu" || state === "over")) { startGame(); return; }
      if (e.code === "KeyP" && (state === "playing" || state === "paused")) {
        state = state === "playing" ? "paused" : "playing";
        msgEl.innerHTML = state === "paused" ? "<h1>PAUSED</h1>Press P to carry on" : "";
        return;
      }
      if (state !== "playing") return;
      if (e.code === "ArrowLeft" || e.code === "KeyA") lane = Math.max(0, lane - 1);
      if (e.code === "ArrowRight" || e.code === "KeyD") lane = Math.min(2, lane + 1);
      if ((e.code === "ArrowUp" || e.code === "KeyW" || e.code === "Space") && player.position.y === 0) {
        vy = JUMP_SPEED;
        slideTime = 0;
        beep(520, 0.08, "square", 0.12);
      }
      if (e.code === "ArrowDown" || e.code === "KeyS") {
        slideTime = 0.7;
        if (player.position.y > 0) vy = -14;                      // dive back down
      }
    });
  12. [Obj 1, 6] Add one update function per state; updatePlaying() holds the difficulty curve.
    // ---------- one update function per state ----------
    function updatePlaying(dt) {
      elapsed += dt;
      speed = Math.min(MAX_SPEED, 12 + elapsed * 0.35);           // difficulty curve: faster and faster
      distance += speed * dt;
      spawnTimer -= dt;
      if (spawnTimer <= 0) {
        spawnRow();
        const gap = Math.max(9, 18 - elapsed * 0.1);              // rows get closer together
        spawnTimer = gap / speed;
      }
      treeTimer -= dt;
      if (treeTimer <= 0) { spawnTrees(); treeTimer = 0.35; }
      updatePlayer(dt);
      moveWorld(dt);
      checkCollisions();
      scoreEl.textContent = score();
      coinsEl.textContent = coinCount;
    }
    function updateMenu(dt, t) {
      player.position.y = Math.abs(Math.sin(t * 4)) * 0.3;        // jog on the spot
    }
    function updateOver(dt) {
      player.rotation.x = Math.max(-Math.PI / 2, player.rotation.x - 4 * dt);   // fall flat
      player.position.y = Math.max(0, player.position.y - 6 * dt);
    }
  13. [Obj 1] Finish with the animation loop and the resize handler.
    // ---------- animation loop ----------
    const clock = new THREE.Clock();
    showMenu();
    renderer.setAnimationLoop(function () {
      const dt = Math.min(clock.getDelta(), 0.05);
      const t = clock.elapsedTime;
      if (state === "playing") updatePlaying(dt);
      else if (state === "menu") updateMenu(dt, t);
      else if (state === "over") updateOver(dt);
      // ("paused": nothing moves)
      camera.position.x += (player.position.x * 0.5 - camera.position.x) * Math.min(1, 4 * dt);
      renderer.render(scene, camera);
    });
    
    window.addEventListener("resize", function () {
      camera.aspect = window.innerWidth / window.innerHeight;
      camera.updateProjectionMatrix();
      renderer.setSize(window.innerWidth, window.innerHeight);
    });
  14. Save, press Enter and run. Then start planning your final project (Objective 8).
Checkpoint: menu, run, pause and crash states work; lanes, jumps, slides, pooled spawns, speed-up, fog and best score all work (Objectives 1-7).

Marking rubric

CriterionPointsScore
Game states: menu, playing, paused, over3
Lanes, jump and slide with a resizable box3
Fair spawning with object pools3
Scrolling world and road texture2
Difficulty curve, fog and saved best score3
Runs with no console errors1
Total15

Common errors

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