Week 7 — Your First 3D Game
Welcome to 3D. This week you install Node.js, create an npm project, install Three.js with npm install three and run it with the Vite dev server. Then you set up a scene, a camera and a
renderer, build boxes from geometry and materials, and animate them in a game loop — ending with
Cube Stack, a stacking game where every miss trims your tower.
🎯 Objectives
- Install Node.js, install Three.js with
npm install threeand run it with the Vite dev server. - Create a
Scene, aPerspectiveCameraand aWebGLRenderer. - Build a
Meshfrom a geometry and a material. - Position, rotate and size objects with
x,yandz. - Animate with
setAnimationLoopand aClock. - Light a scene with
AmbientLightandDirectionalLight. - Control the game with the keyboard and the mouse.
- Keep the game the right size when the window is resized.
🛠 Weekly tasks
- Objective 1 — install Three.js with npm and run Vite: Activity 1 + build
cubeStack.html. - Objective 2 — create the scene, camera and renderer: Activity 2 + build
cubeStack.html. - Objective 3 — build meshes from geometry and material: Activity 3 + build
cubeStack.html. - Objective 4 — position and rotate objects in 3D: Activity 4 + build
cubeStack.html. - Objective 5 — animate with the render loop and a clock: Activity 5 + build
cubeStack.html. - Objective 6 — add ambient and directional light: Activity 6 + build
cubeStack.html. - Objective 7 — control the game with keys and clicks: Activity 7 + build
cubeStack.html. - Objective 8 — handle window resizing: Activity 8 + build
cubeStack.html. - Examples — build the lecture examples
first3d.html,meshes.html,spin.html,overlapDemo.html, one file per concept, and try each change. (Concepts 1–4) - Build your own
cubeStack_yourname.html— add a best score and a “Perfect!” bonus for near-exact drops. (All objectives)
🎓 Lecture activity Open lecture slides →
A 90-minute session of 35 slides. Each concept is taught four ways: the big idea, a short example with its live 3D output, a line-by-line explanation, and a 5-minute “try it” task. The lab work at 1:00 uses the Lab activity below.
Session plan
- 0:0010 minWarm-upReview questions on last week
- 0:1010 minGame & objectivesThis week’s game, objectives and key words
- 0:2035 minConceptsBig idea → code with live 3D output → line by line → try it
- 0:555 minCheck understandingCommon mistakes and a 4-question quiz
- 1:0025 minLabBuild the files in the Lab activity below
- 1:255 minWrap-upBuild-your-own task, marking guide and recap
Concepts this week
- 1. Scene, camera, renderer — The three things every 3D page needs
- 2. Meshes — Geometry (shape) + material (look) = mesh
- 3. Move it — Position, rotation and the animation loop
- 4. Stacking logic — Overlap maths: keep only what lands on the block below
The slides open as a page on this site. Press F for full screen, the arrow keys to move, N for speaker notes, and P to save as PDF (turn on “Background graphics”).
🧪 Lab activity: work through the files Printable lab sheet
Set up your Week7 npm project (step 1). Build Cube Stack below, writing the code shown for each step. Everything goes in one file, cubeStack.html, inside a single <script type="module">. Start with the four example files from the lecture (one per concept), then build the game.
npm install three, and the Vite dev server (npx vite) serves your files at http://localhost:5173/ and reloads them when you save. Opening an HTML file by double-clicking shows a blank page. New to Node.js? Week 7’s first step and the Setup guide show the installation.-
Install Node.js and create the Week7 project Objective 1
Week7\ — Node.js, npm, Three.js and Vite (Node.js is installed once for the whole course).
- [Obj 1] Install Node.js: go to
https://nodejs.org, download the LTS version for Windows, and run the installer with the default options. It also installs npm, the Node package manager. (Skip this if your lab PC already has it.) - [Obj 1] Open a new terminal (VS Code: Terminal → New Terminal, or Ctrl+`) and check both programs answer with a version number:
node -v npm -v - [Obj 1] Create a folder named
Week7, open it in VS Code (File → Open Folder…), then open the terminal again: it now starts insideWeek7. Create an npm project. This writespackage.json, the file that lists what your project needs:npm init -y - [Obj 1] Install Three.js. npm downloads it into a new
node_modulesfolder and records it inpackage.json. We use version 0.170.0 (r170) all course:npm install three@0.170.0 - [Obj 1] Install Vite, a small development server.
--save-devmeans it is a tool for building, not part of the game itself:npm install --save-dev vite@5 - [Obj 1] Open
package.json. It should now list both packages (your version numbers may differ slightly):{ "name": "week7", ... "dependencies": { "three": "^0.170.0" }, "devDependencies": { "vite": "^5.4.0" } } - [Obj 1] Start Vite and leave the terminal running. It prints an address such as
http://localhost:5173/. Each HTML file you create is opened at that address plus its name, for examplehttp://localhost:5173/first3d.html, and reloads every time you save. Stop Vite with Ctrl+C.npx vite - Why does this work? In your files,
import * as THREE from "three"asks for the package by name. Vite findsthreeinnode_modulesand sends it to the browser. A file opened by double-clicking has no Vite, so the page stays blank.
- [Obj 1] Install Node.js: go to
-
first3d.html Concept 1 · Scene, camera, renderer
Week7\first3d.html — The three things every 3D page needs.
- Create
first3d.htmland add this code. Create the three must-haves, add a cube, then render once.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>My First 3D Scene</title> <style> body { margin: 0; overflow: hidden; background: #fffdf8; } </style> </head> <body> <script type="module"> import * as THREE from "three"; // 1. the scene holds everything const scene = new THREE.Scene(); scene.background = new THREE.Color(0xfffdf8); // 2. the camera: field of view, aspect ratio, near and far limits const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100); camera.position.set(1.5, 1.5, 3); // up, to the right and back from the middle camera.lookAt(0, 0, 0); // look at the middle of the scene // 3. the renderer draws onto a <canvas> const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // a cube: a box shape wearing a material that needs no lights const cube = new THREE.Mesh( new THREE.BoxGeometry(1, 1, 1), new THREE.MeshNormalMaterial()); scene.add(cube); // draw one picture renderer.render(scene, camera); // resizing the window clears the picture, so fit the new size and draw again window.addEventListener("resize", function () { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); renderer.render(scene, camera); }); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/first3d.html. You should see one cube, seen from the camera. - [Try it]
- Change
camera.position.set(1.5, 1.5, 3)to(0, 0, 6). - Change the field of view from 75 to 30.
- Change the cube to
BoxGeometry(2, 0.5, 1).
- Change
- Create
-
meshes.html Concept 2 · Meshes
Week7\meshes.html — Geometry (shape) + material (look) = mesh.
- Create
meshes.htmland add this code. Lit materials (Lambert, Standard) need a light; MeshBasicMaterial does not.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Three Shapes, Three Materials</title> <style> body { margin: 0; overflow: hidden; background: #fffdf8; } </style> </head> <body> <script type="module"> import * as THREE from "three"; const scene = new THREE.Scene(); scene.background = new THREE.Color(0xfffdf8); const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100); camera.position.set(0, 1.5, 6); camera.lookAt(0, 0, 0); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // an orange box with a matt material (needs light) const box = new THREE.Mesh( new THREE.BoxGeometry(1, 1, 1), new THREE.MeshLambertMaterial({ color: 0xe8823a })); box.position.x = -2; box.rotation.set(0.5, 0.6, 0); // a blue ball with a standard material (needs light) const ball = new THREE.Mesh( new THREE.SphereGeometry(0.6, 32, 16), new THREE.MeshStandardMaterial({ color: 0x2563eb })); // a green cone with a basic material (ignores light, so it looks flat) 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); // lights for the Lambert and Standard materials scene.add(new THREE.AmbientLight(0xffffff, 0.5)); const sun = new THREE.DirectionalLight(0xffffff, 2); sun.position.set(3, 4, 5); scene.add(sun); renderer.render(scene, camera); // resizing the window clears the picture, so fit the new size and draw again window.addEventListener("resize", function () { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); renderer.render(scene, camera); }); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/meshes.html. You should see box, sphere and cone side by side. - [Try it]
- Add a fourth mesh:
TorusGeometry(0.5, 0.2, 16, 48)with aMeshStandardMaterial. - Place it at
y = 1.5, above the ball. - Remove the two lights: which shapes go black?
- Add a fourth mesh:
- Create
-
spin.html Concept 3 · Move it
Week7\spin.html — Position, rotation and the animation loop.
- Create
spin.htmland add this code. clock.getDelta() gives the seconds since the last frame, so speed is the same on every computer.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Spin and Bounce</title> <style> body { margin: 0; overflow: hidden; background: #fffdf8; } </style> </head> <body> <script type="module"> import * as THREE from "three"; const scene = new THREE.Scene(); scene.background = new THREE.Color(0xfffdf8); const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 100); camera.position.set(0, 1.5, 6); camera.lookAt(0, 0.5, 0); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); scene.add(new THREE.AmbientLight(0xffffff, 0.5)); const sun = new THREE.DirectionalLight(0xffffff, 2); sun.position.set(3, 4, 5); scene.add(sun); const cube = new THREE.Mesh(new THREE.BoxGeometry(1.2, 1.2, 1.2), new THREE.MeshLambertMaterial({ color: 0xe8823a })); cube.position.set(-1.5, 0.6, 0); const ball = new THREE.Mesh(new THREE.SphereGeometry(0.5, 32, 16), new THREE.MeshStandardMaterial({ color: 0x2563eb })); ball.position.x = 1.5; const floor = new THREE.Mesh(new THREE.BoxGeometry(6, 0.1, 3), new THREE.MeshLambertMaterial({ color: 0xd8d2c4 })); floor.position.y = -0.55; scene.add(cube, ball, floor); // the animation loop: change things a little, then draw again const clock = new THREE.Clock(); function animate() { const dt = clock.getDelta(); // seconds since the last frame const t = clock.elapsedTime; // seconds since the start cube.rotation.y += 1.5 * dt; // turn 1.5 radians per second cube.rotation.x += 0.5 * dt; ball.position.y = Math.abs(Math.sin(t * 3)) * 1.5; // bounce between 0 and 1.5 renderer.render(scene, camera); } renderer.setAnimationLoop(animate); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/spin.html. You should see a spinning cube and a bouncing ball. - [Try it]
- Make the ball orbit:
ball.position.x = Math.cos(t) * 2andball.position.z = Math.sin(t) * 2. - Remove the bouncing line.
- Double the cube’s turning speed.
- Make the ball orbit:
- Create
-
overlapDemo.html Concept 4 · Stacking logic
Week7\overlapDemo.html — Overlap maths: keep only what lands on the block below.
- Create
overlapDemo.htmland add this code. The green block is what would stay if you dropped the orange block now.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Overlap Demo</title> <style> body { margin: 0; overflow: hidden; background: #fffdf8; font-family: Arial, Helvetica, sans-serif; } #info { position: absolute; left: 16px; top: 12px; font-size: 20px; color: #1b2030; } </style> </head> <body> <div id="info"></div> <script type="module"> import * as THREE from "three"; const scene = new THREE.Scene(); scene.background = new THREE.Color(0xfffdf8); const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100); camera.position.set(0, 3, 9); camera.lookAt(0, 0.5, 0); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); scene.add(new THREE.AmbientLight(0xffffff, 0.6)); const sun = new THREE.DirectionalLight(0xffffff, 1.5); sun.position.set(5, 10, 7); scene.add(sun); const WIDTH = 3; // both blocks are 3 wide // the grey block already on the stack const base = new THREE.Mesh(new THREE.BoxGeometry(WIDTH, 0.5, 3), new THREE.MeshLambertMaterial({ color: 0x8a90a0 })); scene.add(base); // the orange block sliding above it (see-through, so we can see the green part) const moving = new THREE.Mesh(new THREE.BoxGeometry(WIDTH, 0.5, 3), new THREE.MeshLambertMaterial({ color: 0xe8823a, transparent: true, opacity: 0.45 })); moving.position.y = 1.2; scene.add(moving); // the green block: what would stay if we dropped the orange block now const keep = new THREE.Mesh(new THREE.BoxGeometry(1, 0.5, 3), new THREE.MeshLambertMaterial({ color: 0x12854f })); keep.position.y = 0.5; scene.add(keep); const info = document.getElementById("info"); const clock = new THREE.Clock(); renderer.setAnimationLoop(function () { const t = clock.getElapsedTime(); moving.position.x = Math.sin(t * 0.8) * 4; // slide left and right const delta = moving.position.x - base.position.x; // how far off centre const overlap = WIDTH - Math.abs(delta); // how much still sits on the base keep.visible = overlap > 0; // no overlap = a miss if (overlap > 0) { keep.scale.x = overlap; // the box is 1 wide, so scale = width keep.position.x = base.position.x + delta / 2; // centre of the overlap } info.textContent = "delta = " + delta.toFixed(2) + " overlap = " + Math.max(0, overlap).toFixed(2); renderer.render(scene, camera); }); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/overlapDemo.html. You should see the moving block and its trimmed result. - [Try it]
- Change
WIDTHto 2: how often is there no green block? - Change the sliding speed 0.8 to 2.
- Snap near misses: if
Math.abs(delta) < 0.3, set the green block to the full width.
- Change
- Create
-
cubeStack.html Objectives 1–8
Week7\cubeStack.html — the stacking game.
- [Obj 1] Create
cubeStack.htmlwith this scaffold. There is no need to say where Three.js is:import … from "three"is found by Vite innode_modules.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Cube Stack</title> <style> body { margin: 0; overflow: hidden; background: #10141f; font-family: Arial, Helvetica, sans-serif; } #hud { position: absolute; top: 12px; left: 0; right: 0; text-align: center; color: #ffffff; pointer-events: none; } #score { font-size: 48px; font-weight: bold; } #msg { font-size: 18px; color: #c9cfe0; } </style> </head> <body> <div id="hud"> <div id="score">0</div> <div id="msg">Click or press Space to drop the block</div> </div> <script type="module"> import * as THREE from "three"; // TODO: steps 2-7 go here </script> </body> </html> - [Obj 2] Replace the TODO with the scene, the camera and the renderer. The camera sits up and to the side, looking at the middle.
// ---------- scene, camera, renderer ---------- const scene = new THREE.Scene(); scene.background = new THREE.Color(0x10141f); const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100); camera.position.set(6, 6, 10); camera.lookAt(0, 0, 0); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); - [Obj 6] Add two lights: a soft ambient light everywhere and a directional “sun”.
// ---------- light (more about lights next week) ---------- scene.add(new THREE.AmbientLight(0xffffff, 0.6)); const sun = new THREE.DirectionalLight(0xffffff, 1.5); sun.position.set(5, 10, 7); scene.add(sun); - [Obj 3, 4] Add the game settings and
makeBlock(). Each block is aMeshwith its ownBoxGeometry;userData.widthremembers its width for the maths later.// ---------- game settings ---------- const BLOCK_H = 0.5; // height of every block const DEPTH = 3; // every block is 3 units deep (z) const RANGE = 4; // how far the moving block slides left and right let speed = 3; // sliding speed in units per second let stack = []; // blocks already placed let moving = null; // the block sliding back and forth let direction = 1; // 1 = moving right, -1 = moving left let score = 0; let gameOver = false; const scoreEl = document.getElementById("score"); const msgEl = document.getElementById("msg"); // Make one block: a box mesh with a colour that changes with the level function makeBlock(width, x, y, level) { const geometry = new THREE.BoxGeometry(width, BLOCK_H, DEPTH); const colour = new THREE.Color().setHSL((level * 0.07) % 1, 0.7, 0.55); const material = new THREE.MeshLambertMaterial({ color: colour }); const block = new THREE.Mesh(geometry, material); block.position.set(x, y, 0); block.userData.width = width; // remember the width for the overlap maths scene.add(block); return block; } - [Obj 3, 4] Add
addMovingBlock(),startGame()anddropBlock().dropBlock()keeps only the overlapping part of the block.// Start a new block at the left, as wide as the block on top function addMovingBlock() { const top = stack[stack.length - 1]; const level = stack.length; moving = makeBlock(top.userData.width, -RANGE, level * BLOCK_H, level); direction = 1; } function startGame() { stack.forEach(function (b) { scene.remove(b); }); if (moving) scene.remove(moving); stack = [makeBlock(3, 0, 0, 0)]; // the base block score = 0; speed = 3; gameOver = false; scoreEl.textContent = score; msgEl.textContent = "Click or press Space to drop the block"; addMovingBlock(); } // Drop the moving block: keep only the part that overlaps the block below function dropBlock() { if (gameOver) { startGame(); return; } const top = stack[stack.length - 1]; const delta = moving.position.x - top.position.x; // how far off centre const overlap = top.userData.width - Math.abs(delta); if (overlap <= 0) { // missed completely gameOver = true; msgEl.textContent = "Game over! Click or press Space to play again"; 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)); score++; scoreEl.textContent = score; speed += 0.15; // a little harder each time addMovingBlock(); } - [Obj 4, 5] Add the animation loop. It slides the block, lets a missed block fall, raises the camera and draws the frame.
// ---------- animation loop ---------- const clock = new THREE.Clock(); function animate() { const dt = clock.getDelta(); // seconds since the last frame if (!gameOver) { moving.position.x += direction * speed * dt; if (moving.position.x > RANGE) direction = -1; if (moving.position.x < -RANGE) direction = 1; } else { moving.position.y -= 5 * dt; // the missed block falls away moving.rotation.z += 2 * dt; } // the camera rises smoothly as the stack grows const topY = stack.length * BLOCK_H; camera.position.y += (6 + topY - camera.position.y) * 0.05; camera.lookAt(0, topY - 1, 0); renderer.render(scene, camera); } renderer.setAnimationLoop(animate); - [Obj 7, 8] Finish with the input listeners, the resize handler and a call to
startGame().// ---------- input ---------- window.addEventListener("keydown", function (e) { if (e.code === "Space") { e.preventDefault(); dropBlock(); } }); window.addEventListener("pointerdown", dropBlock); // ---------- keep the right size ---------- window.addEventListener("resize", function () { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); }); startGame(); - Save and open
http://localhost:5173/cubeStack.html. Play a few rounds and check the console (F12) shows no errors.
- [Obj 1] Create
📝 Tasks for this file:
Click or press Space to drop the block. The preview uses the class copy of Three.js; your own files use the three package that npm installed in your Week7 folder.
📚 Node.js, npm and Vite in one minute
- Node.js runs JavaScript outside the browser. We use it for its tools, not in the game itself.
- npm installs packages:
npm install three@0.170.0puts Three.js innode_modulesand records it inpackage.json. - Vite (
npx vite) serves your folder athttp://localhost:5173/, finds"three"innode_modules, and reloads the page when you save. - Do not hand in
node_modules(it is big).package.jsonis enough:npm installdownloads everything again. - Later,
npx vite buildpacks a finished game into adistfolder you can put on any web server.