WEEK 10

Web Games Development · 3D with Three.js

3D Collision Detection

Bounding boxes, walls you slide along, pick-ups and hazards: build a maze game from a text map.

Box3

intersectsBox

walls

pick-ups

level map

Game: Coin Collector

Today · 90 minutes

Plan for the session

StartSegmentTime
0:00Warm-up review10 min
0:10This week’s game and objectives10 min
0:20Concepts: idea, code, line by line, try it35 min
0:55Common mistakes and check your understanding5 min
1:00Lab: build the game25 min
1:25Build-your-own task, recap and exit quiz5 min

Week 10 · 3D Collision Detection

2 / 35

Warm-up · 5 minutes

Remember Week 9?

1

Why build the car with a Group?

2

A car faces angle a. Which way is forward?

3

What does camera.position.lerp(target, 0.1) do?

4

In Park It!, how did we detect a bump?

Week 10 · 3D Collision Detection

3 / 35

This week’s game

Grab every coin, dodge the spikes

You are the green cube in a maze. Walls block you, but you can slide along them when you hold two keys.

Collect all seven gold coins as fast as you can. Spiky balls patrol the long corridors and bounce off the walls.

A spike costs a life and makes you blink for a moment. Lose three lives and the game is over. Press B to see every collision box.

HOW TO PLAY

Enter to start.
Arrow keys / WASD to move.
B shows the bounding boxes.


YOU WILL BUILD

  • coinCollector.html
  • package.json

Week 10 · 3D Collision Detection

4 / 35

Objectives

By the end of Week 10 you can…

01

Describe objects with Box3 bounding boxes.

02

Build boxes with setFromObject / setFromCenterAndSize.

03

Test overlaps with intersectsBox.

04

Stop at walls but slide along them.

05

Collect pick-ups and remove them safely.

06

Patrolling hazards, lives and invulnerability.

07

Build a level from a text map.

08

Show boxes with Box3Helper to debug.

Week 10 · 3D Collision Detection

5 / 35

Key words this week

Vocabulary

TermMeaning
bounding boxThe smallest box that fits around an object
Box3Three.js bounding box with min and max corners
axis-alignedLined up with x, y and z; never tilted
intersectsBoxtrue if two boxes overlap
setFromObjectFit a box around a mesh (slower, exact)
setFromCenterAndSizeMake a box from a point and a size (fast)
pick-upAn item collected by touching it
invulnerableBriefly safe from damage after a hit

Week 10 · 3D Collision Detection

6 / 35

What the program must do

What a maze game needs

A level

Walls built from a text map.

Solid walls

The player cannot pass through, but slides along.

Pick-ups

Coins that disappear and score when touched.

Danger

Patrolling spikes and a number of lives.

Week 10 · 3D Collision Detection

7 / 35

Big idea 1 · Bounding boxes

Wrap every object in a simple box

1

min and max

Two corners: the lowest x, y, z and the highest.

2

axis-aligned

The box never rotates; it grows to fit instead.

3

cheap to test

Six number comparisons say if two boxes touch.

Week 10 · 3D Collision Detection

8 / 35

Example 1 · Bounding boxes

A box around a spinning shape

The yellow box is recalculated every frame. Notice it never tilts: it grows instead.

CODE · box3.html

const knot = new THREE.Mesh(
  new THREE.TorusKnotGeometry(0.8, 0.25, 100, 16),
  new THREE.MeshStandardMaterial({ color: 0x2563eb }));
scene.add(knot);

const box = new THREE.Box3();
scene.add(new THREE.Box3Helper(box, 0xffcc00));

// in the loop:
knot.rotation.x += 0.6 * dt;
knot.rotation.y += 0.9 * dt;
box.setFromObject(knot);       // fit the box again
console.log(box.min, box.max);

OUTPUT · a turning torus knot inside its Box3

Week 10 · 3D Collision Detection

9 / 35

Line by line · Example 1

A box around a spinning shape

new THREE.Box3()

An empty box; it is filled in later.

new THREE.Box3Helper(box, colour)

Draws the box as yellow lines (for debugging).

box.setFromObject(knot)

Fit the box tightly around the mesh as it is now.

box.min / box.max

Vector3 corners: smallest and largest x, y, z.

setFromCenterAndSize(c, size)

Or make a box directly from a centre and a size.

Week 10 · 3D Collision Detection

10 / 35

Try it · 5 minutes

Box a different shape

  1. Replace the knot with a long BoxGeometry(3, 0.3, 0.3).
  2. Watch the box as it turns.
  3. When is the box the smallest?

YOU SHOULD SEE

A thin stick inside a box that grows to a big cube as the stick turns, and shrinks again when the stick lines up with an axis.

Week 10 · 3D Collision Detection

11 / 35

Big idea 2 · Overlap tests

Two boxes touch if they overlap on every axis

1

x

a.min.x ≤ b.max.x and a.max.x ≥ b.min.x

2

y

…the same for y…

3

z

…and for z. One gap on any axis = no touch.

Week 10 · 3D Collision Detection

12 / 35

Example 2 · Overlap tests

Turn red when touching

Two boxes slide past each other; the overlap test runs every frame.

CODE · overlap.html

const boxA = new THREE.Box3();
const boxB = new THREE.Box3();
const size = new THREE.Vector3(1, 1, 1);

// in the loop:
a.position.x = Math.sin(t) * 2.5;
b.position.z = Math.cos(t * 1.3) * 2.5;
boxA.setFromCenterAndSize(a.position, size);
boxB.setFromCenterAndSize(b.position, size);

const hit = boxA.intersectsBox(boxB);
a.material.color.set(hit ? 0xff3333 : 0x2563eb);
b.material.color.set(hit ? 0xff3333 : 0x12854f);

OUTPUT · two moving cubes that turn red when they overlap

Week 10 · 3D Collision Detection

13 / 35

Line by line · Example 2

Turn red when touching

const size = new THREE.Vector3(1, 1, 1)

The width, height and depth of each cube.

boxA.setFromCenterAndSize(a.position, size)

Move the box to where the cube is now.

boxA.intersectsBox(boxB)

true if the two boxes overlap (or touch).

hit ? 0xff3333 : 0x2563eb

Red while touching, normal colour otherwise.

box.containsPoint(p)

Another test: is a single point inside the box?

Week 10 · 3D Collision Detection

14 / 35

Try it · 5 minutes

Make a near-miss

  1. Set b.position.y = 1.1.
  2. Do they still turn red when they cross?
  3. Now set it to 0.9.

YOU SHOULD SEE

At 1.1 they pass over each other with no hit (a gap on the y axis). At 0.9 they overlap and turn red.

Week 10 · 3D Collision Detection

15 / 35

Big idea 3 · Walls and sliding

Try a move; if it hits a wall, take it back

1

move x

Change x, update the box, test the walls; undo x if hit.

2

move z

Then the same for z, on its own.

3

slide

Blocked on one axis, still free on the other.

Week 10 · 3D Collision Detection

16 / 35

Example 3 · Walls and sliding

Stop at the wall, slide along it

The green cube always pushes diagonally (right and up); the wall only blocks one of those.

CODE · coinCollector.html · movePlayer()

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

function hitsWall(box) {
  return wallBoxes.some(function (w) { return w.intersectsBox(box); });
}

OUTPUT · pushing diagonally into a wall makes the cube slide

Week 10 · 3D Collision Detection

17 / 35

Line by line · Example 3

Stop at the wall, slide along it

player.position.x += dx * SPEED * dt

Try the x part of the move on its own.

updatePlayerBox()

Move the box to the new position first.

if (hitsWall(playerBox)) … -=

Inside a wall? Take the x move back.

…then the same for z

z is tested separately, so it can still move.

wallBoxes.some(…)

true if the box hits at least one wall.

Week 10 · 3D Collision Detection

18 / 35

Try it · 5 minutes

Feel the difference

  1. In movePlayer(), move x and z together, then test once.
  2. If it hits, undo both.
  3. Walk diagonally into a wall. Then change it back.

YOU SHOULD SEE

With one combined test, the cube sticks to walls when you hold two keys. With separate tests it slides.

Week 10 · 3D Collision Detection

19 / 35

Big idea 4 · Levels from text

Draw the level with your keyboard

1

MAP

An array of strings: one string per row.

2

loop

For every row and column, read one character.

3

build

# makes a wall, C a coin, S a spike, P the start.

Week 10 · 3D Collision Detection

20 / 35

Example 4 · Levels from text

Build a maze from strings

Each character is one 2 × 2 tile. tileToWorld turns (column, row) into x and z.

CODE · coinCollector.html · build

const MAP = [
  "#######",
  "#P..C.#",
  "#.#.#.#",
  "#C..S.#",
  "#######",
];
const TILE = 2;
MAP.forEach(function (line, row) {
  for (let col = 0; col < line.length; col++) {
    const p = tileToWorld(col, row);
    if (line[col] === "#") addWall(p);
    else if (line[col] === "C") addCoin(p);
  }
});

OUTPUT · a small level built from six strings

Week 10 · 3D Collision Detection

21 / 35

Line by line · Example 4

Build a maze from strings

const MAP = [ "#######", … ]

Each string is one row of the level.

MAP.forEach(function (line, row)

Visit every row, with its row number.

line[col]

One character: the tile at this column.

tileToWorld(col, row)

Column × 2 → x, row × 2 → z, centred on (0, 0).

if (line[col] === "#") addWall(p)

Choose what to build from the character.

Week 10 · 3D Collision Detection

22 / 35

Try it · 5 minutes

Redesign the maze

  1. In Coin Collector, change some . to # and # to .
  2. Add two extra C coins in new places.
  3. Make sure every coin can still be reached!

YOU SHOULD SEE

Your own maze, with the total coin count in the HUD updating automatically.

Week 10 · 3D Collision Detection

23 / 35

Common mistakes

When it goes wrong, check these first

The player walks through walls

Fix: Update the player box (setFromCenterAndSize) after moving and before testing.

The player sticks to walls

Fix: Move and test x and z separately, and only undo the axis that hit.

Some coins are skipped when collecting

Fix: Loop backwards (i = coins.length − 1 down to 0) when you splice items out of the array.

All lives vanish at once

Fix: Use an invulnerability timer so one touch costs one life.

Week 10 · 3D Collision Detection

24 / 35

Check your understanding · 1 of 4

What does a Box3 store?

A

A centre and a radius

B

Two corners: min and max

C

A colour

D

A rotation

Week 10 · 3D Collision Detection

25 / 35

Check your understanding · 2 of 4

Why test x and z movement separately?

A

It is faster

B

So the player can slide along walls

C

Box3 only works on x

D

To save memory

Week 10 · 3D Collision Detection

26 / 35

Check your understanding · 3 of 4

Why loop backwards when removing coins?

A

Coins are stored backwards

B

Removing an item shifts the later ones, so going forwards skips one

C

It is the only way splice works

D

To spin them

Week 10 · 3D Collision Detection

27 / 35

Check your understanding · 4 of 4

In the map, what does each character become?

A

A pixel

B

One 2 × 2 tile: wall, coin, spike, start or floor

C

A sound

D

A colour

Week 10 · 3D Collision Detection

28 / 35

Check your understanding

Answers

QAnswerWhy
Q1B · Two corners: min and maxBox3 has min and max Vector3 corners.
Q2B · So the player can slide along wallsBlocked on one axis, the other can still move.
Q3B · Removing an item shifts the later ones, so going forwards skips oneAfter splice(i, 1), the next item moves into position i.
Q4B · One 2 × 2 tile: wall, coin, spike, start or floortileToWorld turns column and row into x and z.

Week 10 · 3D Collision Detection

29 / 35

Lab time · 25 minutes

Your workflow for 3D files

1

Folder

Create a folder named Week10 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 coinCollector_yourname.html.

Week 10 · 3D Collision Detection

30 / 35

Lab activity · coinCollector.html

Build Coin Collector in ten steps

StepObjectivesCheckpoint
Scaffold + scene, lights—Dark-blue window, no errors
MAP, tileToWorld, floor7A flat floor the size of the map
Build walls, coins, spikes from the map1, 2, 7, 8The maze appears
makeSpike()6Spiky balls in two corridors
Player + box helpers1, 2, 8A green cube at P
Keyboard (and the B key)8B shows the boxes
movePlayer()3, 4Walls block; diagonal slides
updateCoins()3, 5Coins vanish and count
updateSpikes()3, 6Spikes patrol; lives drop
Game state + loop5, 6Win and lose messages

Week 10 · 3D Collision Detection

31 / 35

Stuck?

A five-step 3D debugging checklist

  1. Open the console (F12) and read the first red error.
  2. Blank page? Check npx vite is running and you opened http://localhost:5173/…, not the file itself.
  3. “Failed to resolve import three”? Run npm install in the week folder.
  4. Check the spelling and capitals: THREE.BoxGeometry, not THREE.boxGeometry.
  5. Nothing visible? Check the camera is not inside or behind the object.

THIS WEEK’S TIP

Press B: if the yellow player box and a wall box overlap while you are standing still, the wall box or the player size is wrong.

Week 10 · 3D Collision Detection

32 / 35

BUILD YOUR OWN · ALL OBJECTIVES

Make it yours: your own level, a key and a door

Week10\coinCollector_yourname.html

Week 10 · 3D Collision Detection

33 / 35

How the build-your-own task is marked

Marking guide

CriterionWhat we look forMarks
Runs cleanlyRuns with npx vite with no console errors2
Required featuresNew level; key opens the door; best time saved4
Readable codeIndented, sensible names, a comment on each function2
Your own touchNew hazards, colours, sounds or pick-ups2
Total10

Week 10 · 3D Collision Detection

34 / 35

Recap · Week 10

What you can do now

  • Box3: min and max corners, always axis-aligned.
  • setFromObject (exact) or setFromCenterAndSize (fast).
  • intersectsBox for overlaps; Box3Helper to see them.
  • Move one axis at a time to slide along walls.
  • Levels from text maps; remove pick-ups looping backwards.

NEXT WEEK

Week 11 · Mouse Picking

Click on 3D objects with a Raycaster: a Whack-a-Mole game with hover effects and timed spawns.

Week 10 · 3D Collision Detection

35 / 35

Keyboard
→ Space next   ← previous   Home/End first / last
F full screen   N speaker notes   P print / save as PDF
Click the right or left half of a slide to move forward or back.

Save as PDF: press P, choose “Save as PDF”, and turn on “Background graphics”.