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 three and run it with the Vite dev server.
  • Create a Scene, a PerspectiveCamera and a WebGLRenderer.
  • Build a Mesh from a geometry and a material.
  • Position, rotate and size objects with x, y and z.
  • Animate with setAnimationLoop and a Clock.
  • Light a scene with AmbientLight and DirectionalLight.
  • Control the game with the keyboard and the mouse.
  • Keep the game the right size when the window is resized.

🛠 Weekly tasks

  1. Objective 1 — install Three.js with npm and run Vite: Activity 1 + build cubeStack.html.
  2. Objective 2 — create the scene, camera and renderer: Activity 2 + build cubeStack.html.
  3. Objective 3 — build meshes from geometry and material: Activity 3 + build cubeStack.html.
  4. Objective 4 — position and rotate objects in 3D: Activity 4 + build cubeStack.html.
  5. Objective 5 — animate with the render loop and a clock: Activity 5 + build cubeStack.html.
  6. Objective 6 — add ambient and directional light: Activity 6 + build cubeStack.html.
  7. Objective 7 — control the game with keys and clicks: Activity 7 + build cubeStack.html.
  8. Objective 8 — handle window resizing: Activity 8 + build cubeStack.html.
  9. Examples — build the lecture examples first3d.html, meshes.html, spin.html, overlapDemo.html, one file per concept, and try each change. (Concepts 1–4)
  10. 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

  1. 0:0010 minWarm-upReview questions on last week
  2. 0:1010 minGame & objectivesThis week’s game, objectives and key words
  3. 0:2035 minConceptsBig idea → code with live 3D output → line by line → try it
  4. 0:555 minCheck understandingCommon mistakes and a 4-question quiz
  5. 1:0025 minLabBuild the files in the Lab activity below
  6. 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.

3D files run through Vite. Each week is an npm project: Three.js is installed with 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.
  1. 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).

    1. [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.)
    2. [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
    3. [Obj 1] Create a folder named Week7, open it in VS Code (File → Open Folder…), then open the terminal again: it now starts inside Week7. Create an npm project. This writes package.json, the file that lists what your project needs:
      npm init -y
    4. [Obj 1] Install Three.js. npm downloads it into a new node_modules folder and records it in package.json. We use version 0.170.0 (r170) all course:
      npm install three@0.170.0
    5. [Obj 1] Install Vite, a small development server. --save-dev means it is a tool for building, not part of the game itself:
      npm install --save-dev vite@5
    6. [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"
        }
      }
    7. [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 example http://localhost:5173/first3d.html, and reloads every time you save. Stop Vite with Ctrl+C.
      npx vite
    8. Why does this work? In your files, import * as THREE from "three" asks for the package by name. Vite finds three in node_modules and sends it to the browser. A file opened by double-clicking has no Vite, so the page stays blank.
  2. first3d.html Concept 1 · Scene, camera, renderer

    Week7\first3d.html — The three things every 3D page needs.

    1. Create first3d.html and 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>
    2. Save. With npx vite running, open http://localhost:5173/first3d.html. You should see one cube, seen from the camera.
    3. [Try it]
      1. Change camera.position.set(1.5, 1.5, 3) to (0, 0, 6).
      2. Change the field of view from 75 to 30.
      3. Change the cube to BoxGeometry(2, 0.5, 1).
  3. meshes.html Concept 2 · Meshes

    Week7\meshes.html — Geometry (shape) + material (look) = mesh.

    1. Create meshes.html and 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>
    2. Save. With npx vite running, open http://localhost:5173/meshes.html. You should see box, sphere and cone side by side.
    3. [Try it]
      1. Add a fourth mesh: TorusGeometry(0.5, 0.2, 16, 48) with a MeshStandardMaterial.
      2. Place it at y = 1.5, above the ball.
      3. Remove the two lights: which shapes go black?
  4. spin.html Concept 3 · Move it

    Week7\spin.html — Position, rotation and the animation loop.

    1. Create spin.html and 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>
    2. Save. With npx vite running, open http://localhost:5173/spin.html. You should see a spinning cube and a bouncing ball.
    3. [Try it]
      1. Make the ball orbit: ball.position.x = Math.cos(t) * 2 and ball.position.z = Math.sin(t) * 2.
      2. Remove the bouncing line.
      3. Double the cube’s turning speed.
  5. overlapDemo.html Concept 4 · Stacking logic

    Week7\overlapDemo.html — Overlap maths: keep only what lands on the block below.

    1. Create overlapDemo.html and 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>
    2. Save. With npx vite running, open http://localhost:5173/overlapDemo.html. You should see the moving block and its trimmed result.
    3. [Try it]
      1. Change WIDTH to 2: how often is there no green block?
      2. Change the sliding speed 0.8 to 2.
      3. Snap near misses: if Math.abs(delta) < 0.3, set the green block to the full width.
  6. cubeStack.html Objectives 1–8

    Week7\cubeStack.html — the stacking game.

    1. [Obj 1] Create cubeStack.html with this scaffold. There is no need to say where Three.js is: import … from "three" is found by Vite in node_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>
    2. [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);
    3. [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);
    4. [Obj 3, 4] Add the game settings and makeBlock(). Each block is a Mesh with its own BoxGeometry; userData.width remembers 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;
      }
    5. [Obj 3, 4] Add addMovingBlock(), startGame() and dropBlock(). 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();
      }
    6. [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);
    7. [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();
    8. Save and open http://localhost:5173/cubeStack.html. Play a few rounds and check the console (F12) shows no errors.
Finished example output — click the game first so it receives your key presses

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