Week 7 Lab Sheet — Your First 3D Game

Web Games Development · Three.js basics · ~150 minutes

Objectives

  1. Install Node.js, install Three.js with npm install three and run it with the Vite dev server.
  2. Create a Scene, a PerspectiveCamera and a WebGLRenderer.
  3. Build a Mesh from a geometry and a material.
  4. Position, rotate and size objects with x, y and z.
  5. Animate with setAnimationLoop and a Clock.
  6. Light a scene with AmbientLight and DirectionalLight.
  7. Control the game with the keyboard and the mouse.
  8. Keep the game the right size when the window is resized.

Instructions

Set up a Week7 npm project (step 1), keep npx vite running, and open each file at http://localhost:5173/ followed by its name. Build the example files, then the game, writing the code shown. Save after each step and watch the browser reload. Tick each checkpoint.

Files

1. Install Node.js and create the Week7 project Objective 1

Week7\

  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.
Checkpoint: node -v prints a version, package.json lists three and vite, and npx vite shows Local: http://localhost:5173/.

2. first3d.html Concept 1 · Scene, camera, renderer

Week7\first3d.html

  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).
Checkpoint: the cube looks smaller from further away, bigger with a narrow view, and becomes a flat bar.

3. meshes.html Concept 2 · Meshes

Week7\meshes.html

  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?
Checkpoint: a shaded ring above the ball; without lights only the green Basic cone stays visible.

4. spin.html Concept 3 · Move it

Week7\spin.html

  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.
Checkpoint: the ball circles the cube, which spins twice as fast.

5. overlapDemo.html Concept 4 · Stacking logic

Week7\overlapDemo.html

  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.
Checkpoint: narrower blocks miss more often, the slide is faster, and near-perfect positions keep the full width.

6. cubeStack.html Objectives 1–8

Week7\cubeStack.html

  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.
Checkpoint: blocks slide and stack, misses end the game, Space / click and resizing work (Objectives 1-8).

Marking rubric

CriterionPointsScore
npm project with three and vite; runs with npx vite2
Scene, camera and renderer set up3
Blocks built from geometry + material and lit3
Animation loop with dt; overlap logic correct4
Keyboard / mouse input and resizing work2
Runs with no console errors1
Total15

Common errors

Progress and quiz scores are also tracked on the Week 7 lab page in the class website.