WEEK 11

Web Games Development · 3D with Three.js

Mouse Picking

Turn a mouse click into a ray, find the 3D object under it, and build a Whack-a-Mole game.

Raycaster

pointer

intersectObjects

hover

state machine

Game: Whack-a-Mole 3D

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 11 · Mouse Picking

2 / 35

Warm-up · 5 minutes

Remember Week 10?

1

What two corners does a Box3 have?

2

Why test x and z movement separately?

3

How did we show the collision boxes?

4

How did the Week 5 memory game know which card was clicked?

Week 11 · Mouse Picking

3 / 35

This week’s game

Bonk them before they hide

Nine holes, one hammer. Moles pop up at random and only stay up for a moment, less and less as the game goes on.

Move the mouse: the hammer slides across the board and a mole under the mouse glows. Click to whack it: a squash and a point.

Golden moles are worth 3. Clicking an empty hole counts as a miss. You have 45 seconds.

HOW TO PLAY

Click to start.
Move the mouse to aim the hammer.
Click a mole to whack it.


YOU WILL BUILD

  • whackAMole.html
  • package.json

Week 11 · Mouse Picking

4 / 35

Objectives

By the end of Week 11 you can…

01

Convert the mouse position to −1…+1 coordinates.

02

Cast a ray from the camera through the pointer.

03

Find what the ray hits with intersectObjects.

04

Use the closest hit: object, point, distance.

05

Highlight what is under the mouse.

06

Place things on a surface with intersectPlane.

07

Run moles as state machines with random spawns.

08

Animate feedback: squash and swing.

Week 11 · Mouse Picking

5 / 35

Key words this week

Vocabulary

TermMeaning
RaycasterTests which objects a ray (line) passes through
rayA line starting at a point and going in one direction
NDCNormalised device coordinates: −1 to +1 across the screen
intersectObjectsAll hits along the ray, nearest first
hits[0].pointWhere the ray touched the nearest object
PlaneAn endless flat surface, e.g. y = 0
hoverThe pointer is over something, not clicked yet
state machineAn object that is always in one named state

Week 11 · Mouse Picking

6 / 35

What the program must do

What a whack-a-mole game needs

Picking

Know which 3D mole is under the mouse.

Timing

Moles pop up at random and hide again.

Feedback

A glow on hover, a squash on a hit.

Scoring

Points, misses and a countdown.

Week 11 · Mouse Picking

7 / 35

Big idea 1 · From pixels to a ray

A click is a line shot into the scene

1

pixels

clientX, clientY: from the top-left of the window.

2

−1 … +1

Normalised: centre is (0, 0), y points up.

3

ray

setFromCamera fires a line from the camera through that point.

Week 11 · Mouse Picking

8 / 35

Example 1 · From pixels to a ray

Where does the ray meet the floor?

A pretend pointer circles the screen; the red dot is where its ray hits the floor plane.

CODE · ray.html

const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const floorPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
const hit = new THREE.Vector3();

window.addEventListener("pointermove", function (e) {
  pointer.x = (e.clientX / window.innerWidth) * 2 - 1;
  pointer.y = -(e.clientY / window.innerHeight) * 2 + 1;
  raycaster.setFromCamera(pointer, camera);
  if (raycaster.ray.intersectPlane(floorPlane, hit)) {
    dot.position.copy(hit);
  }
});

OUTPUT · a moving pointer and its ray hitting the floor

Week 11 · Mouse Picking

9 / 35

Line by line · Example 1

Where does the ray meet the floor?

new THREE.Vector2()

Holds the pointer as two numbers, x and y.

(e.clientX / innerWidth) * 2 - 1

Left edge −1, centre 0, right edge +1.

-(e.clientY / innerHeight) * 2 + 1

Flipped: top +1, bottom −1.

raycaster.setFromCamera(pointer, camera)

Aim the ray from the camera through the pointer.

ray.intersectPlane(plane, hit)

Where the ray crosses a flat plane (or null).

Week 11 · Mouse Picking

10 / 35

Try it · 5 minutes

Print the pointer

  1. In Whack-a-Mole, add console.log(pointer.x, pointer.y) in setPointer().
  2. Move the mouse to each corner of the game.
  3. Write down the four pairs of numbers.

YOU SHOULD SEE

About (−1, 1) top-left, (1, 1) top-right, (−1, −1) bottom-left and (1, −1) bottom-right.

Week 11 · Mouse Picking

11 / 35

Big idea 2 · What did I hit?

Ask the ray what it passes through

1

intersectObjects

Test the ray against a list of objects.

2

sorted

Hits come back nearest first: hits[0] is in front.

3

each hit

.object (the mesh), .point (where), .distance (how far).

Week 11 · Mouse Picking

12 / 35

Example 2 · What did I hit?

The ray sweeps, the nearest cube lights up

The marker shows hits[0].point: the exact spot where the ray enters the nearest cube.

CODE · pick.html

raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(cubes, true);

cubes.forEach(function (c) { c.material.color.set(0x2563eb); });
if (hits.length > 0) {
  const first = hits[0];                  // nearest
  first.object.material.color.set(0xff3333);
  marker.position.copy(first.point);      // where
  console.log(first.distance);            // how far
}

OUTPUT · a sweeping ray; the first cube it touches turns red

Week 11 · Mouse Picking

13 / 35

Line by line · Example 2

The ray sweeps, the nearest cube lights up

raycaster.intersectObjects(list, true)

Every hit, nearest first; true = test children too.

hits.length > 0

Did the ray hit anything at all?

hits[0].object

The nearest mesh the ray touched.

hits[0].point

The exact 3D point where it touched.

while (…) obj = obj.parent

Climb from the eye or nose up to the whole mole.

Week 11 · Mouse Picking

14 / 35

Try it · 5 minutes

Report each hit

  1. In moleUnderPointer(), log hits[0].object.geometry.type.
  2. Click a mole’s eye, then its body, then the board.
  3. What do you see each time?

YOU SHOULD SEE

SphereGeometry for the eye, CapsuleGeometry for the body and BoxGeometry for the board.

Week 11 · Mouse Picking

15 / 35

Big idea 3 · Hover and click

Show the player what they will hit

1

pointermove

Ray-cast on every move; remember what is hovered.

2

feedback

Glow with emissive; cursor becomes a pointer.

3

pointerdown

Ray-cast again and act on what was hit.

Week 11 · Mouse Picking

16 / 35

Example 3 · Hover and click

Highlight, then pop

The pretend pointer glides over the balls; the hovered one glows and gets “clicked”.

CODE · hover.html

let hovered = null;
window.addEventListener("pointermove", function (e) {
  setPointer(e);
  const hits = raycaster.intersectObjects(balls);
  hovered = hits.length ? hits[0].object : null;
  balls.forEach(function (b) {
    b.material.emissive.set(b === hovered ? 0x664422 : 0x000000);
  });
  document.body.style.cursor = hovered ? "pointer" : "default";
});
window.addEventListener("pointerdown", function () {
  if (hovered) hovered.scale.setScalar(0.01);    // pop!
});

OUTPUT · hover highlights and clicks that pop the balls

Week 11 · Mouse Picking

17 / 35

Line by line · Example 3

Highlight, then pop

let hovered = null;

Remember what is under the mouse between events.

hovered = hits.length ? hits[0].object : null

The nearest hit, or nothing.

emissive.set(b === hovered ? … : 0x000000)

Glow only the hovered ball; turn the others off.

document.body.style.cursor = "pointer"

The hand cursor says “you can click this”.

pointerdown → hovered

Act on the object the player can see is selected.

Week 11 · Mouse Picking

18 / 35

Try it · 5 minutes

A stronger highlight

  1. In updateMole(), also scale the hovered mole to 1.1.
  2. Make sure it goes back to 1 when not hovered.
  3. Does the game feel easier?

YOU SHOULD SEE

The mole under the mouse grows a little and glows, and shrinks back when the mouse moves away.

Week 11 · Mouse Picking

19 / 35

Big idea 4 · State machines

Each mole is always in exactly one state

1

state

A word in userData: "down", "rising", "up", "hit", "falling".

2

update

Each frame, do what that state does.

3

switch

Change state when a timer or position says so.

Week 11 · Mouse Picking

20 / 35

Example 4 · State machines

One mole, four states

The label shows the current state as the mole goes round the cycle.

CODE · whackAMole.html · updateMole()

if (u.state === "rising") {
  m.position.y = Math.min(UP_Y, m.position.y + RISE_SPEED * dt);
  if (m.position.y === UP_Y) { u.state = "up"; u.timer = upTime; }
} else if (u.state === "up") {
  u.timer -= dt;
  if (u.timer <= 0) u.state = "falling";
} else if (u.state === "falling") {
  m.position.y = Math.max(DOWN_Y, m.position.y - RISE_SPEED * dt);
  if (m.position.y === DOWN_Y) u.state = "down";
}

OUTPUT · a mole cycling through its states

Week 11 · Mouse Picking

21 / 35

Line by line · Example 4

One mole, four states

u.state === "rising"

Only the code for the current state runs.

Math.min(UP_Y, y + RISE_SPEED * dt)

Move up, but never past the top.

if (m.position.y === UP_Y) …

Reached the top: switch to "up" and start the timer.

u.timer -= dt; if (u.timer <= 0)

Time is up: start falling.

spawn(): filter "down", pick at random

Only hidden moles can pop up.

Week 11 · Mouse Picking

22 / 35

Try it · 5 minutes

Add a cheeky state

  1. Add a "peek" state: rise only to y = −0.3.
  2. Wait 0.4 s, then go back down.
  3. Use it for 1 in 5 spawns.

YOU SHOULD SEE

Some moles just peek out and vanish again, which makes players hesitate.

Week 11 · Mouse Picking

23 / 35

Common mistakes

When it goes wrong, check these first

Clicks hit the wrong place

Fix: Use window.innerWidth / innerHeight in the pointer formula, and do not forget the minus sign for y.

Clicking a mole’s eye does nothing

Fix: Pass true to intersectObjects to test children, then climb .parent up to the mole group.

You can hit moles that are hidden

Fix: Include the board in the list: it is hit first, so hits[0] is not a mole.

Every mole glows at once

Fix: Moles sharing one material share its emissive. Give each mole its own material.

Week 11 · Mouse Picking

24 / 35

Check your understanding · 1 of 4

The mouse is in the exact centre of the window. What is the pointer?

A

(1, 1)

B

(0, 0)

C

(−1, −1)

D

(0.5, 0.5)

Week 11 · Mouse Picking

25 / 35

Check your understanding · 2 of 4

What does raycaster.setFromCamera(pointer, camera) do?

A

Moves the camera

B

Aims the ray from the camera through the pointer

C

Draws a line

D

Takes a screenshot

Week 11 · Mouse Picking

26 / 35

Check your understanding · 3 of 4

intersectObjects returns hits in which order?

A

Random

B

Biggest first

C

Nearest first

D

The order of the list

Week 11 · Mouse Picking

27 / 35

Check your understanding · 4 of 4

Why does each mole have a "state"?

A

To save memory

B

So it always does exactly one thing: rise, wait, fall…

C

Three.js needs it

D

To make it gold

Week 11 · Mouse Picking

28 / 35

Check your understanding

Answers

QAnswerWhy
Q1B · (0, 0)The centre of the screen is (0, 0) in normalised coordinates.
Q2B · Aims the ray from the camera through the pointerIt sets the ray’s start (the camera) and direction (through the pointer).
Q3C · Nearest firsthits[0] is always the closest object.
Q4B · So it always does exactly one thing: rise, wait, fall…A state machine keeps each mole’s behaviour clear.

Week 11 · Mouse Picking

29 / 35

Lab time · 25 minutes

Your workflow for 3D files

1

Folder

Create a folder named Week11 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 whackAMole_yourname.html.

Week 11 · Mouse Picking

30 / 35

Lab activity · whackAMole.html

Build Whack-a-Mole 3D in ten steps

StepObjectivesCheckpoint
Scaffold + scene, lights—Sky-blue window, no errors
Board and nine holes—A green board with black holes
makeMole()7Moles hidden inside the board
Hammer6A hammer stands on the board
Raycaster + moleUnderPointer()1, 2, 3, 4Ready to pick
pointermove + pointerdown3, 5, 6Hammer follows; clicks counted
updateMole()5, 7, 8States, glow and squash
spawn()7Moles pop up at random
Game state7Score, misses, time
Animation loop8The hammer swings

Week 11 · Mouse Picking

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

Add scene.add(new THREE.ArrowHelper(raycaster.ray.direction, raycaster.ray.origin, 20, 0xff0000)) inside a click to see where the ray actually went.

Week 11 · Mouse Picking

32 / 35

BUILD YOUR OWN · ALL OBJECTIVES

Make it yours: bombs, combos, best score

Week11\whackAMole_yourname.html

Week 11 · Mouse Picking

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 featuresBomb, combo and best score all work4
Readable codeIndented, sensible names, a comment on each function2
Your own touchNew mole designs, sounds, colours or a level2
Total10

Week 11 · Mouse Picking

34 / 35

Recap · Week 11

What you can do now

  • Pointer → normalised −1…+1 coordinates (flip y!).
  • Raycaster.setFromCamera aims a ray through the pointer.
  • intersectObjects: hits nearest first; .object, .point, .distance.
  • ray.intersectPlane places things on a surface.
  • Hover feedback and state machines make games feel alive.

NEXT WEEK

Week 12 · Gravity & Projectiles

Aim a cannon, fire with velocity and gravity, and knock down a tower of blocks.

Week 11 · Mouse Picking

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”.