Week 14 — Final Project: Endless Runner
The last game brings everything together. Lane Runner is an endless runner: switch lanes, jump and slide past obstacles while the world rushes towards you, faster and faster. You organise the game into states (menu, playing, paused, over), recycle objects with an object pool, scroll the road texture, tune a difficulty curve, add fog, and save a best score — then plan your own final project.
🎯 Objectives
- Organise a game with states (menu, playing, paused, over) and one update function per state.
- Move between lanes smoothly, jump with gravity and slide with a smaller collision box.
- Spawn rows of obstacles and coins with a timer, always leaving a way through.
- Reuse objects with an object pool (a
classwithget()andrelease()). - Move the world towards the player and scroll a texture with
offset. - Design a difficulty curve: speed and spawn rate increase over time, up to a limit.
- Add atmosphere with
Fogand keep a best score withlocalStorage. - Plan, build and present your own 3D game as the final project.
🛠 Weekly tasks
- Objective 1 — organise the game into states: Activity 1 + build
laneRunner.html. - Objective 2 — switch lanes, jump and slide: Activity 2 + build
laneRunner.html. - Objective 3 — spawn rows of obstacles and coins: Activity 3 + build
laneRunner.html. - Objective 4 — recycle objects with a pool: Activity 4 + build
laneRunner.html. - Objective 5 — move the world and scroll the road: Activity 5 + build
laneRunner.html. - Objective 6 — make the game harder over time: Activity 6 + build
laneRunner.html. - Objective 7 — add fog and a saved best score: Activity 7 + build
laneRunner.html. - Objective 8 — plan your final project: Activity 8 + build
laneRunner.html. - Examples — build the lecture examples
statesDemo.html,lanesDemo.html,poolDemo.html,difficultyDemo.html, one file per concept, and try each change. (Concepts 1–4) - Build your own
laneRunner_yourname.html— design, build and present your own 3D game (see the final project brief). (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
- 0:0010 minWarm-upReview questions on last week
- 0:1010 minGame & objectivesThis week’s game, objectives and key words
- 0:2035 minConceptsBig idea → code with live 3D output → line by line → try it
- 0:555 minCheck understandingCommon mistakes and a 4-question quiz
- 1:0025 minLabBuild the files in the Lab activity below
- 1:255 minWrap-upBuild-your-own task, marking guide and recap
Concepts this week
- 1. Game states — menu → playing ⇄ paused → over
- 2. Lanes, jump, slide — Three positions, gravity and a smaller box
- 3. Object pools — Reuse objects instead of creating new ones
- 4. Difficulty and atmosphere — Speed curve, spawn gap, fog, best score
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 Week14 npm project (step 1). Build Lane Runner below, writing the code shown for each step, all in one file, laneRunner.html. Then use it as a starting point (or inspiration) for your final project. Start with the four example files from the lecture (one per concept), then build the game.
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.-
Set up your Week14 project npm · Vite
Week14\ — a new npm project, once at the start of the week.
- Create a folder named
Week14, open it in VS Code, and open the terminal with Ctrl+`. - 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 - Shortcut: download
package.jsonfrom Materials for this week into the folder, then runnpm installinstead. - 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
- Create a folder named
-
statesDemo.html Concept 1 · Game states
Week14\statesDemo.html — menu → playing ⇄ paused → over.
- Create
statesDemo.htmland 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 · P: pause / carry on · 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> - Save. With
npx viterunning, openhttp://localhost:5173/statesDemo.html. You should see the label change state as you press the keys, and the runner behave differently in each state. - [Try it]
- Add a "ready" state after Enter that lasts 3 seconds, then switches to "playing".
- Show 3, 2, 1 in the label during "ready".
- Make R go from "over" back to "menu".
- Create
-
lanesDemo.html Concept 2 · Lanes, jump, slide
Week14\lanesDemo.html — Three positions, gravity and a smaller box.
- Create
lanesDemo.htmland 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 · Up or Space: jump · 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> - Save. With
npx viterunning, openhttp://localhost:5173/lanesDemo.html. You should see the runner glide between three lanes, jump and land, and squash down to slide. - [Try it]
- Add a double jump: allow a second jump in mid-air (count jumps, reset on landing).
- Make the glide slower: change 12 to 4.
- Add a fourth and fifth lane.
- Create
-
poolDemo.html Concept 3 · Object pools
Week14\poolDemo.html — Reuse objects instead of creating new ones.
- Create
poolDemo.htmland 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> - Save. With
npx viterunning, openhttp://localhost:5173/poolDemo.html. You should see objects streaming past; “made” stops growing. - [Try it]
- Spawn twice as often (0.35 → 0.15): how high does “made” go?
- Remove the
pool.release(obj)line: what happens to “made”? - Put it back and add a second pool for small yellow coins.
- Create
-
difficultyDemo.html Concept 4 · Difficulty and atmosphere
Week14\difficultyDemo.html — Speed curve, spawn gap, fog, best score.
- Create
difficultyDemo.htmland 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> - Save. With
npx viterunning, openhttp://localhost:5173/difficultyDemo.html. You should see speed rising to its limit; posts emerging from fog. - [Try it]
- Change
TIME_SCALEto 1 (real time). - Change the curve to start at 8 and climb by 0.6 per second.
- Move the fog closer:
Fog(…, 8, 25).
- Change
- Create
-
laneRunner.html Objectives 1–7
Week14\laneRunner.html — the endless runner.
- Create
laneRunner.htmlwith 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> - [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); - [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); - [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)); } - [Obj 4] Add the
Poolclass 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"]; - [Obj 3] Add
spawnRow()(one or two blocked lanes, coins in a free lane) andspawnTrees().// ---------- 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); }); } - [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 } }); } - [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); } } } - 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); } - [Obj 1, 7] Add the game states:
showMenu(),startGame()(which releases everything back to the pools) andcrash(), 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 · 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() + " · Best " + best + "<br><br>Press Enter to run again"; } - [Obj 1, 2] Add the keyboard.
e.repeatis 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 } }); - [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); } - [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); }); - Save, press Enter and run. Then start planning your final project (Objective 8).
- Create
📝 Tasks for this file:
Click the game and press Enter. Change lane with ← →, jump with ↑ or Space, slide with ↓, pause with P.
📚 Final project checklist
- Plan — a one-page game design document: idea, rules, controls, win / lose, a sketch.
- Build — start from the closest weekly game; get a playable loop working first, then add features.
- Use at least five techniques from Weeks 7–14 (for example: states, Box3 collisions, raycasting, projectile physics, canvas textures, Web Audio, object pools).
- Polish — a HUD, sound, a start screen and a game-over screen, and no console errors.
- Present — a 3-minute demo, one piece of code explained, and what you would add next.