WEEK 14
Web Games Development · 3D with Three.js
Final Project: Endless Runner
Game states, lanes, object pooling and a difficulty curve: put the whole course together.
game states
lanes
object pool
difficulty
final project
Game: Lane Runner
Today · 90 minutes
Plan for the session
| Start | Segment | Time |
|---|---|---|
| 0:00 | Warm-up review | 10 min |
| 0:10 | This week’s game and objectives | 10 min |
| 0:20 | Concepts: idea, code, line by line, try it | 35 min |
| 0:55 | Common mistakes and check your understanding | 5 min |
| 1:00 | Lab: build the game | 25 min |
| 1:25 | Build-your-own task, recap and exit quiz | 5 min |
Week 14 · Final Project: Endless Runner
2 / 35
Warm-up · 5 minutes
Remember Weeks 7–13?
1
Which three things does every Three.js page need?
2
Which test checks if two boxes overlap?
3
How do you make a texture tile?
4
When can a web page start playing sound?
Week 14 · Final Project: Endless Runner
3 / 35
This week’s game
Run, dodge, collect, survive
You run down a three-lane road. The road, obstacles, coins and trees all rush towards you, and keep speeding up.
Red barriers: jump. Orange bars: slide. Grey walls: change lane. There is always at least one way through.
Coins are worth 10 points, and distance adds points too. Your best score is saved. P pauses the game.
HOW TO PLAY
Enter to run. Left / Right change lane.
Up or Space jump, Down slide.
P to pause.
YOU WILL BUILD
- laneRunner.html
- package.json
Week 14 · Final Project: Endless Runner
4 / 35
Objectives
By the end of Week 14 you can…
01
Organise the game into states with one update each.
02
Lanes, jumping with gravity and sliding.
03
Spawn fair rows of obstacles and coins.
04
Reuse objects with an object pool class.
05
Move the world, scroll the road texture.
06
Design a difficulty curve with limits.
07
Add fog; save a best score.
08
Plan, build and present your own 3D game.
Week 14 · Final Project: Endless Runner
5 / 35
Key words this week
Vocabulary
| Term | Meaning |
|---|---|
| game state | Which part of the game is running: menu, play, pause, over |
| endless runner | A game where the world scrolls forever and speeds up |
| spawn | Bring a new object into the game |
| object pool | A store of objects reused instead of re-created |
| difficulty curve | How quickly a game gets harder over time |
| Fog | Fades distant objects into a colour |
| localStorage | Browser storage that survives closing the page |
| game design document | A short plan of a game: idea, rules, controls, art |
Week 14 · Final Project: Endless Runner
6 / 35
What the program must do
What an endless runner needs
Structure
Menu, play, pause and game-over states.
Movement
Lanes, jumping and sliding.
Endless content
Spawned rows, recycled with pools.
Challenge
A rising speed and a best score to beat.
Week 14 · Final Project: Endless Runner
7 / 35
Big idea 1 · Game states
A whole game is a state machine too
1
state
One variable: "menu", "playing", "paused" or "over".
2
update
The loop calls the update for the current state only.
3
switch
Keys and events change the state: Enter, P, a crash.
Week 14 · Final Project: Endless Runner
8 / 35
Example 1 · Game states
One update per state
The demo goes round menu → playing → paused → playing → over on a timer.
CODE · laneRunner.html · animation loop
let state = "menu";
renderer.setAnimationLoop(function () {
const dt = Math.min(clock.getDelta(), 0.05);
if (state === "playing") updatePlaying(dt);
else if (state === "menu") updateMenu(dt, t);
else if (state === "over") updateOver(dt);
// "paused": nothing moves
renderer.render(scene, camera);
});
// P toggles pause, but only while playing or paused
if (e.code === "KeyP" && (state === "playing" || state === "paused"))
state = state === "playing" ? "paused" : "playing";
OUTPUT · the same scene behaving differently in each state
Week 14 · Final Project: Endless Runner
9 / 35
Line by line · Example 1
One update per state
let state = "menu";
The game always starts on the menu.
if (state === "playing") updatePlaying(dt)
Only the current state’s update runs.
// "paused": nothing moves
No update at all, but we still render.
state === "playing" ? "paused" : "playing"
P switches between the two.
crash() → state = "over"
Events also change the state.
Week 14 · Final Project: Endless Runner
10 / 35
Try it · 5 minutes
Add a countdown state
- Add a "ready" state between menu and playing.
- Show 3, 2, 1 in msgEl for one second each.
- Then switch to "playing".
YOU SHOULD SEE
Pressing Enter shows a 3-2-1 countdown before the run starts.
Week 14 · Final Project: Endless Runner
11 / 35
Big idea 2 · Lanes, jump, slide
Three lanes are simpler than free movement
1
lane
A number 0, 1 or 2; the keys change it by one.
2
glide
x moves towards LANES[lane] a bit each frame.
3
jump / slide
vy and gravity for jumps; a squashed box to slide.
Week 14 · Final Project: Endless Runner
12 / 35
Example 2 · Lanes, jump, slide
Glide, jump and slide
The demo runner changes lane, jumps and slides on its own.
CODE · laneRunner.html · updatePlayer()
const LANES = [-2.5, 0, 2.5];
let lane = 1, vy = 0, slideTime = 0;
function updatePlayer(dt) {
player.position.x += (LANES[lane] - player.position.x)
* Math.min(1, 12 * dt); // glide
vy -= GRAVITY * dt; // fall
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; // slide
}
// jump only from the ground:
if (up && player.position.y === 0) vy = JUMP_SPEED;
OUTPUT · a runner switching lanes, jumping and sliding
Week 14 · Final Project: Endless Runner
13 / 35
Line by line · Example 2
Glide, jump and slide
(LANES[lane] - x) * Math.min(1, 12 * dt)
Close part of the gap each frame: a smooth glide.
vy -= GRAVITY * dt
The same gravity as Week 12.
Math.max(0, y + vy * dt)
Never fall through the road.
player.scale.y = slideTime > 0 ? 0.5 : 1
Squash the runner while sliding.
if (… && player.position.y === 0)
Only jump when standing on the road.
Week 14 · Final Project: Endless Runner
14 / 35
Try it · 5 minutes
Double jump
- Add let jumps = 0; reset it on landing.
- Allow a jump when jumps < 2.
- Make the second jump a little weaker.
YOU SHOULD SEE
Press jump again in mid-air for a second, smaller hop.
Week 14 · Final Project: Endless Runner
15 / 35
Big idea 3 · Object pools
Recycle, do not throw away
1
get()
Take a hidden object from the free list (or make one).
2
use
Place it, make it visible, move it along.
3
release()
Hide it and put it back on the free list.
Week 14 · Final Project: Endless Runner
16 / 35
Example 3 · Object pools
A pool class
The counter shows how few objects are ever made, however long it runs.
CODE · laneRunner.html · class Pool
class Pool {
constructor(create) {
this.create = create; // 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);
}
}
OUTPUT · objects streaming past; “made” stops growing
Week 14 · Final Project: Endless Runner
17 / 35
Line by line · Example 3
A pool class
this.free.pop() || this.create()
Reuse a free object, or make one if none are left.
obj.visible = true
Show it again (it was hidden in the pool).
this.active.push(obj)
Remember it is in play, so it gets moved.
this.active.splice(…indexOf(obj), 1)
Take it out of the active list…
this.free.push(obj)
…and keep it for the next get().
Week 14 · Final Project: Endless Runner
18 / 35
Try it · 5 minutes
Count your objects
- Add console.log for each pool’s active.length + free.length when you crash.
- Play for a minute.
- How many coins were made in total?
YOU SHOULD SEE
Only a few dozen of each, even though hundreds of coins went past.
Week 14 · Final Project: Endless Runner
19 / 35
Big idea 4 · Difficulty and atmosphere
Start easy, get harder, never impossible
1
curve
speed = 12 + time × 0.35, up to MAX_SPEED.
2
spacing
Rows get closer together, but never closer than 9 units.
3
fair
Never block all three lanes; fog hides the spawning.
Week 14 · Final Project: Endless Runner
20 / 35
Example 4 · Difficulty and atmosphere
Faster and faster, inside the fog
The speed climbs to the limit, then the demo resets. Watch the posts appear out of the fog.
CODE · laneRunner.html · updatePlaying()
scene.fog = new THREE.Fog(0x87ceeb, 25, 75); // colour, start, end
elapsed += dt;
speed = Math.min(MAX_SPEED, 12 + elapsed * 0.35);
distance += speed * dt;
spawnTimer -= dt;
if (spawnTimer <= 0) {
spawnRow();
const gap = Math.max(9, 18 - elapsed * 0.1);
spawnTimer = gap / speed; // time = distance / speed
}
OUTPUT · speed rising to its limit; posts emerging from fog
Week 14 · Final Project: Endless Runner
21 / 35
Line by line · Example 4
Faster and faster, inside the fog
new THREE.Fog(colour, 25, 75)
Clear up to 25 units away, fully fogged at 75.
Math.min(MAX_SPEED, 12 + elapsed * 0.35)
Faster every second, but never above the limit.
Math.max(9, 18 - elapsed * 0.1)
Rows closer together, but never closer than 9.
spawnTimer = gap / speed
Turn a distance into a time at the current speed.
localStorage.setItem("laneRunnerBest", best)
Keep the best score after the page closes.
Week 14 · Final Project: Endless Runner
22 / 35
Try it · 5 minutes
Tune the curve
- Make the game start at 8 and climb by 0.6 per second.
- Lower MAX_SPEED to 24.
- Play three runs: is it still fun after a minute?
YOU SHOULD SEE
A gentler start that ramps up faster but tops out lower: often a better curve for beginners.
Week 14 · Final Project: Endless Runner
23 / 35
Common mistakes
When it goes wrong, check these first
The game slows down after a while
Fix: Release objects when they pass the camera, and reuse them with a pool instead of creating new ones.
Sometimes there is no way through
Fix: Never block all three lanes in one row, and keep a minimum gap between rows.
Things keep moving while paused
Fix: Only call updatePlaying() when state === "playing".
The player can fly by holding jump
Fix: Only allow a jump when player.position.y === 0, and ignore e.repeat.
Week 14 · Final Project: Endless Runner
24 / 35
Check your understanding · 1 of 4
What does the "paused" state do in the loop?
A
Stops rendering
B
Runs no update, but still renders
C
Resets the game
D
Shows the menu
Week 14 · Final Project: Endless Runner
25 / 35
Check your understanding · 2 of 4
Why use an object pool?
A
To reuse objects instead of creating and deleting them
B
To add shadows
C
To make the textures repeat
D
Three.js requires it
Week 14 · Final Project: Endless Runner
26 / 35
Check your understanding · 3 of 4
speed = Math.min(32, 12 + t * 0.35). What is the speed after 100 seconds?
A
12
B
35
C
32
D
47
Week 14 · Final Project: Endless Runner
27 / 35
Check your understanding · 4 of 4
Why is the player’s z position always 0?
A
It is a bug
B
The world moves towards the player instead
C
z cannot change in Three.js
D
For the fog
Week 14 · Final Project: Endless Runner
28 / 35
Check your understanding
Answers
| Q | Answer | Why |
|---|---|---|
| Q1 | B · Runs no update, but still renders | Nothing moves, but the frame is still drawn. |
| Q2 | A · To reuse objects instead of creating and deleting them | Recycling avoids slow-downs from making and deleting objects. |
| Q3 | C · 32 | 12 + 35 = 47, but Math.min caps it at 32. |
| Q4 | B · The world moves towards the player instead | Moving the world keeps the camera and player simple. |
Week 14 · Final Project: Endless Runner
29 / 35
Lab time · 25 minutes
Your workflow for 3D files
1
Folder
Create a folder named Week14 and open it in VS Code.
2
Install
In the terminal: npm init -y, npm install three, npm install -D vite.
3
Run
npx vite starts the dev server. Leave it running.
4
Open
http://localhost:5173/ plus the file name, e.g. /first3d.html.
5
Check
Save with Ctrl+S; the page reloads. Open the console (F12).
Each week is an npm project: Vite finds “three” in node_modules, so a double-clicked file shows a blank page. Build the four example files first, then the game; work on a copy named laneRunner_yourname.html.
Week 14 · Final Project: Endless Runner
30 / 35
Lab activity · laneRunner.html
Build Lane Runner in eleven stages
| Step | Objectives | Checkpoint |
|---|---|---|
| Scaffold + scene, fog, lights | 7 | A blue sky, no errors |
| Road texture and grass | 5 | A three-lane road |
| Player, lanes, jump, slide, box | 2 | A runner on the road |
| Pool class + five pools | 4 | Ready to recycle |
| spawnRow(), spawnTrees() | 3 | Fair rows of obstacles |
| moveWorld() | 4, 5 | Everything rushes past |
| checkCollisions() | 2 | Crashes and coin pick-ups |
| Sound effects | — | Ding, jump, crash |
| Game states | 1, 7 | Menu, crash screen, best score |
| Keyboard | 1, 2 | Lanes, jump, slide, pause |
| Update functions + loop | 1, 6 | Speeds up over time |
Week 14 · Final Project: Endless Runner
31 / 35
Stuck?
A five-step 3D debugging checklist
- Open the console (F12) and read the first red error.
- Blank page? Check npx vite is running and you opened http://localhost:5173/…, not the file itself.
- “Failed to resolve import three”? Run npm install in the week folder.
- Check the spelling and capitals: THREE.BoxGeometry, not THREE.boxGeometry.
- Nothing visible? Check the camera is not inside or behind the object.
THIS WEEK’S TIP
Press P to pause, then in the console (with window.pools = pools added) check pools.coin.active.length and pools.coin.free.length.
Week 14 · Final Project: Endless Runner
32 / 35
BUILD YOUR OWN · ALL OBJECTIVES
Final project: your own 3D game
Week14\laneRunner_yourname.html
- Write a one-page game design document: idea, rules, controls, how you win or lose.
- Build it with Three.js using at least five techniques from Weeks 7–14 (states, collisions, physics, picking, textures, sound, pools…).
- Present a 3-minute demo: play it, show one piece of code you are proud of, and say what you would add next.
Week 14 · Final Project: Endless Runner
33 / 35
How the build-your-own task is marked
Marking guide
| Criterion | What we look for | Marks |
|---|---|---|
| Design document | Clear idea, rules, controls and win / lose conditions | 3 |
| Techniques used | At least five Weeks 7–14 techniques, used correctly | 6 |
| Playability | Runs with no console errors; fair, with a clear goal and feedback | 4 |
| Code quality | Organised into functions and states, commented, sensible names | 4 |
| Polish & creativity | Your own art (textures / models), sound, HUD and ideas | 3 |
| Total | 20 |
Week 14 · Final Project: Endless Runner
34 / 35
Recap · Week 14
What you can do now
- Organise games with states and one update per state.
- Lanes, jumping and sliding with gravity and a resizable box.
- Object pools recycle obstacles, coins and scenery.
- A difficulty curve with limits keeps it fair; fog hides spawns.
- Seven weeks of 3D: you can now build complete Three.js games.
NEXT WEEK
Your final project
Plan it, build it, polish it, present it. Use the lab pages from Weeks 7–14 as your toolbox.
Week 14 · Final Project: Endless Runner
35 / 35