WEEK 07

Web Games Development · 3D with Three.js

Your First 3D Game

Scene, camera and renderer: build a 3D stacking game with Three.js.

scene

camera

renderer

mesh

animation loop

Game: Cube Stack

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 7 · Your First 3D Game

2 / 35

Warm-up · 5 minutes

Remember Weeks 1–6?

1

Which canvas method draws a filled rectangle?

2

How did the bouncing ball move on screen?

3

In 2D canvas, which way does y increase?

4

Which event fires when a key is pressed?

Week 7 · Your First 3D Game

3 / 35

This week’s game

Stack the blocks as high as you can

A block slides left and right above the tower. Drop it, and only the part that lands on the block below stays; the rest is cut off.

Each new block is as wide as what is left, and it slides a little faster. Miss completely and the game is over.

Only one new rule: the overlap maths. Everything else is the 3D set-up you learn today.

HOW TO PLAY

Click or press Space to drop.
Click again to restart.


YOU WILL BUILD

  • cubeStack.html
  • package.json

Week 7 · Your First 3D Game

4 / 35

Objectives

By the end of Week 7 you can…

01

Install Three.js with npm and run it with Vite.

02

Create a scene, a perspective camera and a renderer.

03

Build a mesh from a geometry and a material.

04

Position and rotate objects in x, y and z.

05

Animate with setAnimationLoop and a Clock.

06

Light a scene with ambient and directional light.

07

Control the game with the keyboard and mouse.

08

Keep the view correct when the window resizes.

Week 7 · Your First 3D Game

5 / 35

Key words this week

Vocabulary

TermMeaning
SceneThe 3D world that holds every object and light
CameraThe viewpoint the scene is drawn from
RendererDraws the scene onto a <canvas> with WebGL
MeshA visible object: geometry + material
GeometryThe shape of an object (box, sphere, …)
MaterialHow the surface looks (colour, shading)
npmNode’s package manager: npm install three downloads Three.js
ViteA dev server: npx vite serves your files and reloads on save

Week 7 · Your First 3D Game

6 / 35

What the program must do

What a stacking game needs

A 3D world

A scene, a camera and a renderer drawing every frame.

Movement

A block that slides left and right, faster each level.

A rule

Keep only the overlap; a full miss ends the game.

Feedback

A score on screen and a camera that rises with the tower.

Week 7 · Your First 3D Game

7 / 35

Big idea 1 · Scene, camera, renderer

Every 3D page needs three things

1

Scene

The stage: holds every object and light.

2

Camera

The eye: where we look from and how wide.

3

Renderer

The painter: draws what the camera sees onto a canvas.

Week 7 · Your First 3D Game

8 / 35

Example 1 · Scene, camera, renderer

Show one cube

Create the three must-haves, add a cube, then render once.

CODE · first3d.html

import * as THREE from "three";

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(
  75, innerWidth / innerHeight, 0.1, 100);
camera.position.set(1.5, 1.5, 3);
camera.lookAt(0, 0, 0);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);

const cube = new THREE.Mesh(
  new THREE.BoxGeometry(1, 1, 1),
  new THREE.MeshNormalMaterial());
scene.add(cube);
renderer.render(scene, camera);

OUTPUT · one cube, seen from the camera

Week 7 · Your First 3D Game

9 / 35

Line by line · Example 1

Show one cube

new THREE.Scene()

An empty 3D world to put things in.

PerspectiveCamera(75, w/h, 0.1, 100)

Field of view in degrees, aspect ratio, near and far limits.

camera.position.set(1.5, 1.5, 3)

Move the eye back (z) and up, so the cube is in front of it.

renderer.domElement

The <canvas> the renderer draws on; add it to the page.

renderer.render(scene, camera)

Draw one picture of the scene from the camera.

Week 7 · Your First 3D Game

10 / 35

Try it · 5 minutes

Move the camera

  1. Change camera.position to (0, 0, 6).
  2. Change the field of view from 75 to 30.
  3. Save and watch Vite reload the page.

YOU SHOULD SEE

The cube looks smaller at z = 6 and bigger again with a narrow (30°) field of view.

Week 7 · Your First 3D Game

11 / 35

Big idea 2 · Meshes

A mesh is a shape wearing a material

1

Geometry

The shape: BoxGeometry, SphereGeometry, ConeGeometry…

2

Material

The look: colour, shiny or matt, lit or not.

3

Mesh

Geometry + material, placed in the scene.

Week 7 · Your First 3D Game

12 / 35

Example 2 · Meshes

Three shapes, three materials

Lit materials (Lambert, Standard) need a light; MeshBasicMaterial does not.

CODE · meshes.html

const box = new THREE.Mesh(
  new THREE.BoxGeometry(1, 1, 1),
  new THREE.MeshLambertMaterial({ color: 0xe8823a }));
box.position.x = -2;

const ball = new THREE.Mesh(
  new THREE.SphereGeometry(0.6, 32, 16),
  new THREE.MeshStandardMaterial({ color: 0x2563eb }));

const cone = new THREE.Mesh(
  new THREE.ConeGeometry(0.6, 1.2, 32),
  new THREE.MeshBasicMaterial({ color: 0x12854f }));
cone.position.x = 2;

scene.add(box, ball, cone);
scene.add(new THREE.AmbientLight(0xffffff, 0.5));
const sun = new THREE.DirectionalLight(0xffffff, 2);
sun.position.set(3, 4, 5);
scene.add(sun);

OUTPUT · box, sphere and cone side by side

Week 7 · Your First 3D Game

13 / 35

Line by line · Example 2

Three shapes, three materials

new THREE.BoxGeometry(1, 1, 1)

A box 1 wide (x), 1 tall (y) and 1 deep (z).

SphereGeometry(0.6, 32, 16)

Radius 0.6; more segments = a smoother ball.

MeshLambertMaterial({ color })

A matt material that is shaded by lights.

box.position.x = -2

Move the box 2 units to the left.

scene.add(box, ball, cone)

Nothing appears until it is added to the scene.

Week 7 · Your First 3D Game

14 / 35

Try it · 5 minutes

Add a fourth shape

  1. Add a TorusGeometry(0.5, 0.2, 16, 48) mesh.
  2. Give it a MeshStandardMaterial in your favourite colour.
  3. Place it at y = 1.5 above the sphere.

YOU SHOULD SEE

A shaded ring floating above the blue ball.

Week 7 · Your First 3D Game

15 / 35

Big idea 3 · Move it

Change it a little, draw it again, repeat

1

position

x right, y up, z towards you.

2

rotation

Turn around x, y or z, in radians.

3

the loop

setAnimationLoop calls your function every frame.

Week 7 · Your First 3D Game

16 / 35

Example 3 · Move it

Spin and bounce

clock.getDelta() gives the seconds since the last frame, so speed is the same on every computer.

CODE · spin.html

const clock = new THREE.Clock();

function animate() {
  const dt = clock.getDelta();       // seconds
  const t = clock.elapsedTime;       // total time

  cube.rotation.y += 1.5 * dt;       // turn
  cube.rotation.x += 0.5 * dt;
  ball.position.y = Math.abs(Math.sin(t * 3)) * 1.5;

  renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);

OUTPUT · a spinning cube and a bouncing ball

Week 7 · Your First 3D Game

17 / 35

Line by line · Example 3

Spin and bounce

new THREE.Clock()

A stopwatch that starts when it is created.

clock.getDelta()

Seconds since the last call, e.g. 0.016 at 60 fps.

cube.rotation.y += 1.5 * dt

Turn 1.5 radians per second around the y axis.

Math.abs(Math.sin(t * 3)) * 1.5

A value that bounces between 0 and 1.5.

renderer.setAnimationLoop(animate)

Call animate before every screen refresh.

Week 7 · Your First 3D Game

18 / 35

Try it · 5 minutes

Make it orbit

  1. Set ball.position.x = Math.cos(t) * 2.
  2. Set ball.position.z = Math.sin(t) * 2.
  3. Remove the bouncing line.

YOU SHOULD SEE

The ball circles around the cube, coming closer and moving away.

Week 7 · Your First 3D Game

19 / 35

Big idea 4 · Stacking logic

Trim the block to what overlaps

1

delta

How far the moving block is from the one below.

2

overlap

width − |delta|; 0 or less is a miss.

3

trim

A new block, overlap wide, centred at top.x + delta / 2.

Week 7 · Your First 3D Game

20 / 35

Example 4 · Stacking logic

Work out the overlap

The green block is what would stay if you dropped the orange block now.

CODE · cubeStack.html · dropBlock()

const top = stack[stack.length - 1];
const delta = moving.position.x - top.position.x;
const overlap = top.userData.width - Math.abs(delta);

if (overlap <= 0) {          // missed completely
  gameOver = true;
  return;
}
scene.remove(moving);        // swap in a trimmed block
const x = top.position.x + delta / 2;
stack.push(makeBlock(overlap, x, moving.position.y, stack.length));

OUTPUT · the moving block and its trimmed result

Week 7 · Your First 3D Game

21 / 35

Line by line · Example 4

Work out the overlap

moving.position.x - top.position.x

delta: positive if we are too far right.

top.userData.width - Math.abs(delta)

overlap: how much still sits on the block below.

if (overlap <= 0)

Nothing overlaps: the game is over.

top.position.x + delta / 2

The centre of the overlapping part.

stack.push(makeBlock(overlap, …))

The trimmed block becomes the new top.

Week 7 · Your First 3D Game

22 / 35

Try it · 5 minutes

Reward a perfect drop

  1. If Math.abs(delta) < 0.1, set delta = 0.
  2. Then the block keeps its full width.
  3. Show "Perfect!" in msgEl.

YOU SHOULD SEE

Near-perfect drops snap into place and the tower stops shrinking.

Week 7 · Your First 3D Game

23 / 35

Common mistakes

When it goes wrong, check these first

The page is completely blank

Fix: You double-clicked the file. Start npx vite and open http://localhost:5173/ plus the file name.

Failed to resolve import "three"

Fix: Three.js is not installed in this folder. Run npm install three@0.170.0 in the week folder (where package.json is).

Everything is black

Fix: Lambert and Standard materials need a light. Add the AmbientLight and DirectionalLight.

The game looks stretched

Fix: Update camera.aspect and call camera.updateProjectionMatrix() when the window resizes.

Week 7 · Your First 3D Game

24 / 35

Check your understanding · 1 of 4

Which three things does every Three.js page need?

A

Canvas, context, loop

B

Scene, camera, renderer

C

Mesh, light, texture

D

HTML, CSS, PHP

Week 7 · Your First 3D Game

25 / 35

Check your understanding · 2 of 4

What is a mesh made of?

A

A scene and a camera

B

A light and a colour

C

A geometry and a material

D

Two triangles

Week 7 · Your First 3D Game

26 / 35

Check your understanding · 3 of 4

Why multiply movement by dt?

A

To make it random

B

So the speed is the same at any frame rate

C

To slow the renderer down

D

Three.js requires it

Week 7 · Your First 3D Game

27 / 35

Check your understanding · 4 of 4

The moving block is 3 wide and 1 unit off-centre. How wide is the trimmed block?

A

1

B

2

C

3

D

4

Week 7 · Your First 3D Game

28 / 35

Check your understanding

Answers

QAnswerWhy
Q1B · Scene, camera, rendererThe scene holds things, the camera looks, the renderer draws.
Q2C · A geometry and a materialGeometry is the shape; material is the look.
Q3B · So the speed is the same at any frame ratedt is the time per frame, so speed × dt is the same distance per second.
Q4B · 2overlap = 3 − |1| = 2.

Week 7 · Your First 3D Game

29 / 35

Lab time · 25 minutes

Your workflow for 3D files

1

Folder

Create a folder named Week7 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 cubeStack_yourname.html.

Week 7 · Your First 3D Game

30 / 35

Lab activity · cubeStack.html

Build Cube Stack in seven steps

StepObjectivesCheckpoint
Scaffold: HUD + module script1Page loads with no console errors
Scene, camera, renderer2An empty dark canvas fills the window
Lights6No errors; lights ready for the blocks
makeBlock()3, 4A coloured box can be created
startGame(), dropBlock()3, 4Base block and a moving block appear
Animation loop5The block slides and the camera rises
Input + resize7, 8Space / click drops; resizing keeps the shape

Week 7 · Your First 3D Game

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

Type scene.children.length in the console? It fails inside a module. Add window.scene = scene; while debugging, then you can inspect it.

Week 7 · Your First 3D Game

32 / 35

BUILD YOUR OWN · ALL OBJECTIVES

Make it yours: best score and perfect drops

Week7\cubeStack_yourname.html

Week 7 · Your First 3D Game

33 / 35

How the build-your-own task is marked

Marking guide

CriterionWhat we look forMarks
Runs cleanlyRuns with npx vite with no errors in the console (F12)2
Required featuresBest score saved and shown; perfect drops snap and give feedback4
Readable codeIndented, sensible names, a comment on each function2
Your own touchColours, speed, camera angle or an extra feature2
Total10

Week 7 · Your First 3D Game

34 / 35

Recap · Week 7

What you can do now

  • Install Three.js with npm; run it with npx vite.
  • Scene + camera + renderer, then renderer.render.
  • Mesh = geometry + material; add it to the scene.
  • Move with position and rotation; animate with setAnimationLoop and dt.
  • Game rules are still plain JavaScript maths.

NEXT WEEK

Week 8 · Shapes, Lights & Shadows

Build a 3D toy room: more shapes, materials, shadows and a camera you can orbit with the mouse.

Week 7 · Your First 3D Game

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