WEEK 09

Web Games Development · 3D with Three.js

Movement & Follow Camera

Build a car from parts, drive it with speed, friction and steering, and chase it with the camera.

Group

speed

sin / cos

Vector3

chase camera

Game: Park It!

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 9 · Movement & Follow Camera

2 / 35

Warm-up · 5 minutes

Remember Week 8?

1

Which three switches are needed for shadows?

2

How do you aim a SpotLight?

3

Why use a keys object instead of reacting only to keydown?

4

What does a.distanceTo(b) give?

Week 9 · Movement & Follow Camera

3 / 35

This week’s game

Drive in, line up, stop

You drive an orange car around a car park. One bay is free: it is green, with a floating arrow above it.

Drive into the bay, line up with the white lines (front or back first), and stop. Hold still for one second and it counts; a new free bay appears.

Bumping a parked car costs two seconds. Park as many times as you can in 90 seconds.

HOW TO PLAY

Enter to start.
Up / W accelerate, Down / S brake and reverse.
Left / Right or A / D steer.


YOU WILL BUILD

  • parkIt.html
  • package.json

Week 9 · Movement & Follow Camera

4 / 35

Objectives

By the end of Week 9 you can…

01

Build one object from many meshes with a Group.

02

Read held-down keys from a key-state object.

03

Model speed, acceleration, friction and top speed.

04

Move the way you face with sin and cos.

05

Use Vector3: clone, add, sub, normalize, copy.

06

Make a chase camera with lerp and lookAt.

07

Keep the player in bounds; bounce off obstacles.

08

Check a goal zone: position, angle and speed.

Week 9 · Movement & Follow Camera

5 / 35

Key words this week

Vocabulary

TermMeaning
GroupAn invisible object that holds other objects
local positionA position measured from the parent group
speed / velocityHow fast (and which way) something moves
accelerationHow fast the speed changes
frictionSlowing down when nothing pushes
Vector3An (x, y, z) value with maths methods
lerpMove part of the way from one value to another
chase cameraA camera that follows behind the player

Week 9 · Movement & Follow Camera

6 / 35

What the program must do

What a driving game needs

A vehicle

A car made of parts that moves as one.

Handling

Speed, friction and steering that feel smooth.

A good view

A camera that stays behind the car.

A goal

A bay to park in, with a clear rule for “parked”.

Week 9 · Movement & Follow Camera

7 / 35

Big idea 1 · Groups

Move the group, the parts come along

1

new THREE.Group()

An empty container with its own position and rotation.

2

group.add(part)

Parts are placed relative to the group (local position).

3

move the group

Turn or move it once; every part follows.

Week 9 · Movement & Follow Camera

8 / 35

Example 1 · Groups

A car from boxes and cylinders

Each part has a local position; rotating the group turns the whole car.

CODE · car.html · module

const car = new THREE.Group();
const body = new THREE.Mesh(
  new THREE.BoxGeometry(1.8, 0.6, 3.6), paint);
body.position.y = 0.6;
car.add(body);

[[-0.95, 1.1], [0.95, 1.1], [-0.95, -1.1], [0.95, -1.1]]
  .forEach(function (p) {
    const wheel = new THREE.Mesh(wheelGeo, wheelMat);
    wheel.rotation.z = Math.PI / 2;     // on its edge
    wheel.position.set(p[0], 0.4, p[1]);
    car.add(wheel);
  });
scene.add(car);

car.rotation.y += 0.5 * dt;             // turns everything

OUTPUT · the car group turning, wheels spinning inside it

Week 9 · Movement & Follow Camera

9 / 35

Line by line · Example 1

A car from boxes and cylinders

const car = new THREE.Group();

An invisible container: the car itself.

body.position.y = 0.6

Local position: 0.6 above the car’s own origin.

wheel.rotation.z = Math.PI / 2

A cylinder stands up; turn it 90° onto its edge.

car.add(wheel)

The wheel now belongs to the car, not the scene.

car.rotation.y += 0.5 * dt

Turn the group: all its parts turn with it.

Week 9 · Movement & Follow Camera

10 / 35

Try it · 5 minutes

Add a spoiler

  1. Make a BoxGeometry(1.8, 0.1, 0.5) mesh.
  2. Set its position to (0, 1.2, -1.7).
  3. Add it to the car group, not to the scene.

YOU SHOULD SEE

A spoiler on the back of the car that turns with it.

Week 9 · Movement & Follow Camera

11 / 35

Big idea 2 · Speed and friction

Keys change the speed, speed changes the position

1

accelerate

speed += ACCEL * dt while a key is held.

2

friction

speed *= 1 − 2 × dt when no key is held.

3

limit

clamp the speed between a reverse and a top speed.

Week 9 · Movement & Follow Camera

12 / 35

Example 2 · Speed and friction

Accelerate, coast and limit

The demo presses “up” for two seconds, then lets go, again and again.

CODE · parkIt.html · drive()

const MAX_SPEED = 12;
const ACCEL = 10;
let speed = 0;

if (up) speed += ACCEL * dt;
if (down) speed -= ACCEL * dt;
if (!up && !down) speed *= 1 - 2 * dt;   // friction

speed = THREE.MathUtils.clamp(
  speed, -MAX_SPEED / 2, MAX_SPEED);

OUTPUT · speeding up to the limit, then coasting to a stop

Week 9 · Movement & Follow Camera

13 / 35

Line by line · Example 2

Accelerate, coast and limit

speed += ACCEL * dt

Gain 10 units/second of speed every second.

speed -= ACCEL * dt

Brake, then reverse.

speed *= 1 - 2 * dt

No key: lose a share of the speed each frame.

THREE.MathUtils.clamp(v, min, max)

Keep a value between two limits.

-MAX_SPEED / 2

Reverse is only half as fast as forward.

Week 9 · Movement & Follow Camera

14 / 35

Try it · 5 minutes

Change the feel

  1. Set ACCEL to 25: what changes?
  2. Change the friction to 1 - 0.5 * dt.
  3. Which feels more like ice, and which like a go-kart?

YOU SHOULD SEE

High ACCEL = snappy go-kart. Low friction = the car slides on for ages, like ice.

Week 9 · Movement & Follow Camera

15 / 35

Big idea 3 · Steering

Turn an angle into a direction

1

angle

rotation.y: which way the car faces.

2

direction

x = sin(angle), z = cos(angle).

3

move

position += direction × speed × dt.

Week 9 · Movement & Follow Camera

16 / 35

Example 3 · Steering

Steer and drive

Steering only works while moving, so the car cannot spin on the spot.

CODE · parkIt.html · drive()

const TURN = 2.2;    // radians per second at full speed
const steer = (left ? 1 : 0) - (right ? 1 : 0);
player.rotation.y += steer * TURN * dt * (speed / MAX_SPEED);

const angle = player.rotation.y;
player.position.x += Math.sin(angle) * speed * dt;
player.position.z += Math.cos(angle) * speed * dt;

OUTPUT · the car steering in a circle; the arrow shows forward

Week 9 · Movement & Follow Camera

17 / 35

Line by line · Example 3

Steer and drive

(left ? 1 : 0) - (right ? 1 : 0)

+1 for left, −1 for right, 0 for both or neither.

* (speed / MAX_SPEED)

No speed, no turning; reversing steers the other way.

const angle = player.rotation.y

The direction the car faces, in radians.

Math.sin(angle) * speed * dt

The sideways (x) part of the movement.

Math.cos(angle) * speed * dt

The forwards (z) part of the movement.

Week 9 · Movement & Follow Camera

18 / 35

Try it · 5 minutes

Tank controls

  1. Remove * (speed / MAX_SPEED) from the steering line.
  2. Drive: what can you do now that you could not before?
  3. Put it back. Why do real cars not do this?

YOU SHOULD SEE

The car can spin on the spot like a tank. Real cars need to roll forward or back to turn.

Week 9 · Movement & Follow Camera

19 / 35

Big idea 4 · Chase camera

A camera that follows smoothly

1

wanted

A point 9 behind and 5 above the car.

2

lerp

Each frame, move part of the way towards it.

3

lookAt

Always point at the car.

Week 9 · Movement & Follow Camera

20 / 35

Example 4 · Chase camera

Behind, above, and smooth

The offset is behind the car, so it uses −sin and −cos of the car’s angle.

CODE · parkIt.html · followCamera()

const camOffset = new THREE.Vector3();
const lookAt = new THREE.Vector3();

function followCamera(dt) {
  const angle = player.rotation.y;
  camOffset.set(-Math.sin(angle) * 9, 5, -Math.cos(angle) * 9);
  const wanted = player.position.clone().add(camOffset);
  camera.position.lerp(wanted, 1 - Math.exp(-4 * dt));
  lookAt.copy(player.position).add(new THREE.Vector3(0, 1, 0));
  camera.lookAt(lookAt);
}

OUTPUT · the camera chasing a car round a figure of eight

Week 9 · Movement & Follow Camera

21 / 35

Line by line · Example 4

Behind, above, and smooth

-Math.sin(angle) * 9, 5, -Math.cos(angle) * 9

Behind the car (minus forward) and 5 up.

player.position.clone().add(camOffset)

clone first, so the car itself does not move.

camera.position.lerp(wanted, a)

Move a fraction a of the way to wanted.

1 - Math.exp(-4 * dt)

A smoothing amount that works at any frame rate.

camera.lookAt(lookAt)

Aim at a point just above the car.

Week 9 · Movement & Follow Camera

22 / 35

Try it · 5 minutes

Change the camera

  1. Change 9 to 15 and 5 to 10: a high, far camera.
  2. Change the 4 in Math.exp(-4 * dt) to 1, then to 20.
  3. Which feels best for parking?

YOU SHOULD SEE

Far and high is easier for parking. 1 = slow and floaty, 20 = almost locked behind the car.

Week 9 · Movement & Follow Camera

23 / 35

Common mistakes

When it goes wrong, check these first

The car drives sideways

Fix: Swap sin and cos, or build the car so its front faces +z (the headlights are at z = 1.81).

The car turns but goes straight

Fix: Move with Math.sin(angle) and Math.cos(angle), not just position.z += speed.

The car also moves when the camera moves

Fix: Use player.position.clone().add(…): add() changes the vector it is called on.

The camera is jumpy

Fix: Use lerp with 1 − Math.exp(−4 × dt) instead of setting camera.position directly.

Week 9 · Movement & Follow Camera

24 / 35

Check your understanding · 1 of 4

Why build the car with a Group?

A

To make it faster

B

So all its parts move and turn together

C

Groups add shadows

D

Meshes cannot be rotated

Week 9 · Movement & Follow Camera

25 / 35

Check your understanding · 2 of 4

The car faces angle a. Which way is forward?

A

(cos a, 0, sin a)

B

(sin a, 0, cos a)

C

(a, 0, a)

D

(0, a, 0)

Week 9 · Movement & Follow Camera

26 / 35

Check your understanding · 3 of 4

What does speed *= 1 - 2 * dt do when no key is held?

A

Stops the car instantly

B

Slowly reduces the speed (friction)

C

Reverses the car

D

Nothing

Week 9 · Movement & Follow Camera

27 / 35

Check your understanding · 4 of 4

Why use camera.position.lerp(wanted, a)?

A

To make the camera follow smoothly

B

To zoom in

C

To add fog

D

To make the car turn

Week 9 · Movement & Follow Camera

28 / 35

Check your understanding

Answers

QAnswerWhy
Q1B · So all its parts move and turn togetherMoving or turning the group moves every part inside it.
Q2B · (sin a, 0, cos a)Forward is x = sin(a), z = cos(a) for a car that faces +z.
Q3B · Slowly reduces the speed (friction)It removes a share of the speed every frame.
Q4A · To make the camera follow smoothlylerp moves the camera part of the way each frame, so it glides.

Week 9 · Movement & Follow Camera

29 / 35

Lab time · 25 minutes

Your workflow for 3D files

1

Folder

Create a folder named Week9 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 parkIt_yourname.html.

Week 9 · Movement & Follow Camera

30 / 35

Lab activity · parkIt.html

Build Park It! in ten steps

StepObjectivesCheckpoint
Scaffold + scene, lights, fog—Sky-blue window, no errors
Car park: ground and lines—Grey ground with white bay lines
makeCar() with a Group1An orange car in the middle
Parked cars, bay, marker1, 8Green bay with an arrow
Keyboard2Enter will start the game
drive()3, 4The car accelerates and steers
collide()5, 7Stays in the car park; bumps cost time
followCamera()5, 6The camera glides behind the car
checkParked()8Bay turns yellow, then counts
Game state + loop3, 8Timer, speed and game over

Week 9 · Movement & Follow Camera

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.AxesHelper(5)): red = x, green = y, blue = z. Check the car’s headlights face the blue (+z) axis at the start.

Week 9 · Movement & Follow Camera

32 / 35

BUILD YOUR OWN · ALL OBJECTIVES

Make it yours: harder bays and a best score

Week9\parkIt_yourname.html

Week 9 · Movement & Follow Camera

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 featuresBest score saved; speed limit warning with a penalty4
Readable codeIndented, sensible names, a comment on each function2
Your own touchCar design, camera, colours or a new level2
Total10

Week 9 · Movement & Follow Camera

34 / 35

Recap · Week 9

What you can do now

  • Group: build once, move once, everything follows.
  • Speed, acceleration, friction and clamp for smooth handling.
  • Move the way you face: sin for x, cos for z.
  • Vector3: clone, add, sub, normalize, copy, distanceTo.
  • Chase camera: lerp to a point behind, then lookAt.

NEXT WEEK

Week 10 · 3D Collision Detection

Bounding boxes (Box3) for walls, coins and spikes in a maze-like Coin Collector.

Week 9 · Movement & Follow Camera

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