Week 9 — Movement & Follow Camera
Time to drive. This week you build a car from several meshes with a Group, give it speed,
acceleration and friction, steer it with Math.sin and Math.cos, and follow it with a
smooth chase camera — all for Park It!, where you squeeze into as many parking bays as you
can in 90 seconds.
🎯 Objectives
- Build one object from several meshes with
THREE.Group. - Read held-down keys from a key-state object.
- Model movement with speed, acceleration, friction and a top speed.
- Move in the direction an object faces with
Math.sinandMath.cos. - Use
Vector3methods:clone,add,sub,normalize,copy. - Make a chase camera that glides behind the player with
lerpandlookAt. - Keep the player inside the level and bounce off obstacles.
- Check a goal zone using position, angle and speed together.
🛠 Weekly tasks
- Objective 1 — build a car from parts with a Group: Activity 1 + build
parkIt.html. - Objective 2 — read the keyboard as held-down keys: Activity 2 + build
parkIt.html. - Objective 3 — add speed, acceleration and friction: Activity 3 + build
parkIt.html. - Objective 4 — steer and move the way the car faces: Activity 4 + build
parkIt.html. - Objective 5 — use Vector3 maths: Activity 5 + build
parkIt.html. - Objective 6 — follow the car with a chase camera: Activity 6 + build
parkIt.html. - Objective 7 — keep the car in bounds and bump off cars: Activity 7 + build
parkIt.html. - Objective 8 — detect a correct park: Activity 8 + build
parkIt.html. - Examples — build the lecture examples
car.html,speedDemo.html,steerDemo.html,chaseCamera.html, one file per concept, and try each change. (Concepts 1–4) - Build your own
parkIt_yourname.html— add a parallel-parking level, skid marks or a best score, and a speed limit warning. (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. Groups — One object made of many meshes
- 2. Speed and friction — Accelerate, coast, brake, top speed
- 3. Steering — Move the way you face with sin and cos
- 4. Chase camera — lerp towards a point behind the player, then lookAt
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 Week9 npm project (step 1). Build Park It! below, writing the code shown for each step, all in one file, parkIt.html. 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.-
Set up your Week9 project npm · Vite
Week9\ — a new npm project, once at the start of the week.
- Create a folder named
Week9, open it in VS Code, and open the terminal with Ctrl+`. - Create the project and install Three.js and Vite (the same commands as Week 7):
npm init -y npm install three@0.170.0 npm install --save-dev vite@5 - Shortcut: download
package.jsonfrom Materials for this week into the folder, then runnpm installinstead. - Start the Vite dev server and leave it running. Open the address it prints plus a file name, for example
http://localhost:5173/car.html. Press Ctrl+C in the terminal to stop it.npx vite
- Create a folder named
-
car.html Concept 1 · Groups
Week9\car.html — One object made of many meshes.
- Create
car.htmland add this code. Each part has a local position; rotating the group turns the whole car.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>A Car from Parts</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(45, window.innerWidth / window.innerHeight, 0.1, 100); camera.position.set(5, 4, 6); camera.lookAt(0, 0.6, 0); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.4)); const sun = new THREE.DirectionalLight(0xffffff, 2); sun.position.set(4, 8, 5); scene.add(sun); const ground = new THREE.Mesh(new THREE.CircleGeometry(4, 48), new THREE.MeshStandardMaterial({ color: 0xd8d2c4 })); ground.rotation.x = -Math.PI / 2; scene.add(ground); // the car is a Group: every part is placed relative to it const car = new THREE.Group(); const body = new THREE.Mesh(new THREE.BoxGeometry(1.8, 0.6, 3.6), new THREE.MeshStandardMaterial({ color: 0xe8823a, roughness: 0.4 })); body.position.y = 0.6; car.add(body); const cabin = new THREE.Mesh(new THREE.BoxGeometry(1.5, 0.55, 1.8), new THREE.MeshStandardMaterial({ color: 0x223344 })); cabin.position.set(0, 1.15, -0.2); car.add(cabin); // each wheel is a small group too (tyre + spoke), so it can spin on its own const wheels = []; const wheelGeo = new THREE.CylinderGeometry(0.4, 0.4, 0.3, 20); const wheelMat = new THREE.MeshStandardMaterial({ color: 0x111111 }); const hubMat = new THREE.MeshStandardMaterial({ color: 0xbbbbbb }); [[-0.95, 1.1], [0.95, 1.1], [-0.95, -1.1], [0.95, -1.1]].forEach(function (p) { const wheel = new THREE.Group(); const tyre = new THREE.Mesh(wheelGeo, wheelMat); tyre.rotation.z = Math.PI / 2; // stand the cylinder on its edge wheel.add(tyre); const spoke = new THREE.Mesh(new THREE.BoxGeometry(0.32, 0.6, 0.1), hubMat); wheel.add(spoke); wheel.position.set(p[0], 0.4, p[1]); car.add(wheel); wheels.push(wheel); }); scene.add(car); const clock = new THREE.Clock(); renderer.setAnimationLoop(function () { const dt = clock.getDelta(); car.rotation.y += 0.5 * dt; // turn the whole car wheels.forEach(function (w) { w.rotation.x += 4 * dt; }); // spin each wheel renderer.render(scene, camera); }); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/car.html. You should see the car group turning, wheels spinning inside it. - [Try it]
- Add a spoiler: a
BoxGeometry(1.8, 0.1, 0.5)at(0, 1.2, -1.7), added to the car group. - Add two headlights at the front (z = 1.81).
- Change the car colour.
- Add a spoiler: a
- Create
-
speedDemo.html Concept 2 · Speed and friction
Week9\speedDemo.html — Accelerate, coast, brake, top speed.
- Create
speedDemo.htmland add this code. Hold the Up key to speed up, let go to coast, hold Down to brake and reverse.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Accelerate, Coast and Limit</title> <style> body { margin: 0; overflow: hidden; background: #fffdf8; font-family: Arial, Helvetica, sans-serif; } #info { position: absolute; left: 16px; top: 12px; font-size: 22px; color: #1b2030; } </style> </head> <body> <div id="info">Hold Up to accelerate, Down to brake</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(40, window.innerWidth / window.innerHeight, 0.1, 200); camera.position.set(0, 6, 18); camera.lookAt(0, 0, 0); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.5)); const road = new THREE.Mesh(new THREE.PlaneGeometry(40, 3), new THREE.MeshStandardMaterial({ color: 0x55585e })); road.rotation.x = -Math.PI / 2; scene.add(road); const car = new THREE.Mesh(new THREE.BoxGeometry(2, 0.8, 1.2), new THREE.MeshStandardMaterial({ color: 0xe8823a })); car.position.y = 0.4; scene.add(car); // keys held down const keys = {}; window.addEventListener("keydown", function (e) { keys[e.code] = true; if (e.code.startsWith("Arrow")) e.preventDefault(); // stop the page scrolling }); window.addEventListener("keyup", function (e) { keys[e.code] = false; }); const MAX_SPEED = 12; const ACCEL = 10; let speed = 0; const info = document.getElementById("info"); const clock = new THREE.Clock(); renderer.setAnimationLoop(function () { const dt = Math.min(clock.getDelta(), 0.1); const up = keys.ArrowUp || keys.KeyW; const down = keys.ArrowDown || keys.KeyS; if (up) speed += ACCEL * dt; // accelerate if (down) speed -= ACCEL * dt; // brake, then reverse if (!up && !down) speed *= 1 - 2 * dt; // friction speed = THREE.MathUtils.clamp(speed, -MAX_SPEED / 2, MAX_SPEED); car.position.x += speed * dt; // speed changes the position if (car.position.x > 18) car.position.x = -18; // wrap round if (car.position.x < -18) car.position.x = 18; info.textContent = (up ? "UP held" : down ? "DOWN held" : "coasting") + " · speed " + speed.toFixed(1); renderer.render(scene, camera); }); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/speedDemo.html. You should see the car speed up to 12, coast to a stop when you let go, and reverse at half speed. - [Try it]
- Set
ACCELto 25: how does it feel? - Change the friction to
1 - 0.5 * dt. - Change
MAX_SPEEDto 20.
- Set
- Create
-
steerDemo.html Concept 3 · Steering
Week9\steerDemo.html — Move the way you face with sin and cos.
- Create
steerDemo.htmland add this code. Drive with the arrow keys or WASD. Steering only works while moving; the dots show your path.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Steer and Drive</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">Arrow keys / WASD: drive and steer. The blue arrow points forward.</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, 16, 10); camera.lookAt(0, 0, 0); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.5)); const ground = new THREE.Mesh(new THREE.PlaneGeometry(30, 20), new THREE.MeshStandardMaterial({ color: 0xd8d2c4 })); ground.rotation.x = -Math.PI / 2; scene.add(ground); // a simple car with an arrow showing its forward direction (+z) const car = new THREE.Group(); const body = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.6, 2.4), new THREE.MeshStandardMaterial({ color: 0xe8823a })); body.position.y = 0.3; car.add(body); car.add(new THREE.ArrowHelper(new THREE.Vector3(0, 0, 1), new THREE.Vector3(0, 0.7, 0), 3, 0x2563eb, 0.6, 0.4)); scene.add(car); const keys = {}; window.addEventListener("keydown", function (e) { keys[e.code] = true; if (e.code.startsWith("Arrow")) e.preventDefault(); // stop the page scrolling }); window.addEventListener("keyup", function (e) { keys[e.code] = false; }); const MAX_SPEED = 8; const TURN = 2.2; // radians per second at full speed let speed = 0; // a trail of dots shows the path const trail = []; const dotGeo = new THREE.SphereGeometry(0.08); const dotMat = new THREE.MeshBasicMaterial({ color: 0xa84c14 }); let frame = 0; const clock = new THREE.Clock(); renderer.setAnimationLoop(function () { const dt = Math.min(clock.getDelta(), 0.1); const up = keys.ArrowUp || keys.KeyW; const down = keys.ArrowDown || keys.KeyS; const left = keys.ArrowLeft || keys.KeyA; const right = keys.ArrowRight || keys.KeyD; if (up) speed += 8 * dt; if (down) speed -= 8 * dt; if (!up && !down) speed *= 1 - 2 * dt; speed = THREE.MathUtils.clamp(speed, -MAX_SPEED / 2, MAX_SPEED); // steer only while moving const steer = (left ? 1 : 0) - (right ? 1 : 0); car.rotation.y += steer * TURN * dt * (speed / MAX_SPEED); // move the way the car faces const angle = car.rotation.y; car.position.x += Math.sin(angle) * speed * dt; car.position.z += Math.cos(angle) * speed * dt; car.position.x = THREE.MathUtils.clamp(car.position.x, -14, 14); car.position.z = THREE.MathUtils.clamp(car.position.z, -9, 9); if (frame++ % 6 === 0 && Math.abs(speed) > 0.5) { const dot = new THREE.Mesh(dotGeo, dotMat); dot.position.copy(car.position); scene.add(dot); trail.push(dot); if (trail.length > 80) scene.remove(trail.shift()); } renderer.render(scene, camera); }); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/steerDemo.html. You should see a car you can drive and steer, leaving a trail, with an arrow pointing forward. - [Try it]
- Remove
* (speed / MAX_SPEED)from the steering line and drive. - Put it back. Why do real cars need it?
- Change
TURNto 4 for tighter turns.
- Remove
- Create
-
chaseCamera.html Concept 4 · Chase camera
Week9\chaseCamera.html — lerp towards a point behind the player, then lookAt.
- Create
chaseCamera.htmland add this code. The offset is behind the car, so it uses −sin and −cos of the car’s angle.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Chase Camera</title> <style> body { margin: 0; overflow: hidden; background: #9fc5e8; } </style> </head> <body> <script type="module"> import * as THREE from "three"; const scene = new THREE.Scene(); scene.background = new THREE.Color(0x9fc5e8); scene.fog = new THREE.Fog(0x9fc5e8, 20, 60); const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 200); camera.position.set(0, 5, -9); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.5)); const ground = new THREE.Mesh(new THREE.PlaneGeometry(100, 100), new THREE.MeshStandardMaterial({ color: 0x55585e })); ground.rotation.x = -Math.PI / 2; scene.add(ground); // traffic cones so you can see the movement for (let i = 0; i < 40; i++) { const cone = new THREE.Mesh(new THREE.ConeGeometry(0.4, 1, 12), new THREE.MeshStandardMaterial({ color: 0xff7a00 })); cone.position.set((Math.random() - 0.5) * 60, 0.5, (Math.random() - 0.5) * 60); scene.add(cone); } // the car drives a figure of eight on its own const car = new THREE.Group(); const body = new THREE.Mesh(new THREE.BoxGeometry(1.8, 0.6, 3.6), new THREE.MeshStandardMaterial({ color: 0xe8823a })); body.position.y = 0.6; const cabin = new THREE.Mesh(new THREE.BoxGeometry(1.5, 0.55, 1.8), new THREE.MeshStandardMaterial({ color: 0x223344 })); cabin.position.set(0, 1.15, -0.2); car.add(body, cabin); scene.add(car); const camOffset = new THREE.Vector3(); const lookAt = new THREE.Vector3(); const previous = new THREE.Vector3(); let t = 0; // the chase camera: glide to a point behind and above the car, then look at it function followCamera(dt) { const angle = car.rotation.y; camOffset.set(-Math.sin(angle) * 9, 5, -Math.cos(angle) * 9); const wanted = car.position.clone().add(camOffset); camera.position.lerp(wanted, 1 - Math.exp(-4 * dt)); lookAt.copy(car.position).add(new THREE.Vector3(0, 1, 0)); camera.lookAt(lookAt); } const clock = new THREE.Clock(); renderer.setAnimationLoop(function () { const dt = Math.min(clock.getDelta(), 0.1); t += dt * 0.5; previous.copy(car.position); car.position.set(Math.sin(t) * 14, 0, Math.sin(2 * t) * 7); // figure of eight car.rotation.y = Math.atan2(car.position.x - previous.x, // face the way it moves car.position.z - previous.z); followCamera(dt); renderer.render(scene, camera); }); </script> </body> </html> - Save. With
npx viterunning, openhttp://localhost:5173/chaseCamera.html. You should see the camera chasing a car round a figure of eight. - [Try it]
- Change the 9 and 5 in
camOffset.set(…)to 15 and 10. - Change the 4 in
Math.exp(-4 * dt)to 1, then 20. - Make the car drive faster:
t += dt * 1.
- Change the 9 and 5 in
- Create
-
parkIt.html Objectives 1–8
Week9\parkIt.html — the parking game.
- Create
parkIt.htmlwith this scaffold.<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Park It!</title> <style> body { margin: 0; overflow: hidden; background: #9fc5e8; font-family: Arial, Helvetica, sans-serif; } #hud { position: absolute; top: 10px; left: 12px; color: #ffffff; font-size: 20px; pointer-events: none; text-shadow: 0 1px 3px #000; } #msg { position: absolute; top: 35%; left: 0; right: 0; text-align: center; color: #ffffff; font-size: 28px; pointer-events: none; text-shadow: 0 2px 6px #000; } </style> </head> <body> <div id="hud">Parked: <span id="parked">0</span> Time: <span id="time">90</span> Speed: <span id="speed">0</span></div> <div id="msg">Park in the green bay as many times as you can<br>Arrow keys / WASD to drive · stop inside the bay<br>Press Enter to start</div> <script type="module"> import * as THREE from "three"; // TODO: the steps below go here </script> </body> </html> - Add the scene with fog, the camera, a renderer with shadows, and a sky-and-ground
HemisphereLightplus a sun.// ---------- scene, camera, renderer ---------- const scene = new THREE.Scene(); scene.background = new THREE.Color(0x9fc5e8); scene.fog = new THREE.Fog(0x9fc5e8, 30, 70); const camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 0.1, 200); const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); renderer.shadowMap.enabled = true; document.body.appendChild(renderer.domElement); scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.2)); const sun = new THREE.DirectionalLight(0xffffff, 2); sun.position.set(10, 20, 8); sun.castShadow = true; sun.shadow.camera.left = -30; sun.shadow.camera.right = 30; sun.shadow.camera.top = 30; sun.shadow.camera.bottom = -30; scene.add(sun); - Add the car park: a big ground plane and the white lines between the bays.
// ---------- the car park ---------- const LOT = 24; // the car park runs from -24 to 24 on x and z const ground = new THREE.Mesh(new THREE.PlaneGeometry(LOT * 2 + 20, LOT * 2 + 20), new THREE.MeshStandardMaterial({ color: 0x55585e })); ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; scene.add(ground); const lineMat = new THREE.MeshBasicMaterial({ color: 0xffffff }); const BAY_X = [-12, -8, -4, 0, 4, 8, 12]; // centres of the parking bays const ROWS = [-14, 14]; // two rows of bays ROWS.forEach(function (z) { for (let x = -14; x <= 14; x += 4) { // white lines between the bays const line = new THREE.Mesh(new THREE.BoxGeometry(0.15, 0.02, 5), lineMat); line.position.set(x, 0.01, z); scene.add(line); } }); - [Obj 1] Add
makeCar(). Every part is added to aGroup, so the whole car moves as one. Its front (headlights) faces +z.// ---------- build a car from parts with a Group ---------- function makeCar(colour) { const car = new THREE.Group(); const paint = new THREE.MeshStandardMaterial({ color: colour, roughness: 0.4 }); const body = new THREE.Mesh(new THREE.BoxGeometry(1.8, 0.6, 3.6), paint); body.position.y = 0.6; const cabin = new THREE.Mesh(new THREE.BoxGeometry(1.5, 0.55, 1.8), new THREE.MeshStandardMaterial({ color: 0x223344, roughness: 0.1 })); cabin.position.set(0, 1.15, -0.2); car.add(body, cabin); const wheelGeo = new THREE.CylinderGeometry(0.4, 0.4, 0.3, 20); const wheelMat = new THREE.MeshStandardMaterial({ color: 0x111111 }); [[-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; // stand the cylinder on its edge wheel.position.set(p[0], 0.4, p[1]); car.add(wheel); }); const lightMat = new THREE.MeshStandardMaterial({ color: 0xffffcc, emissive: 0xffffaa }); [-0.6, 0.6].forEach(function (x) { // headlights show which way is the front (+z) const lamp = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.2, 0.05), lightMat); lamp.position.set(x, 0.65, 1.81); car.add(lamp); }); car.traverse(function (part) { part.castShadow = true; }); scene.add(car); return car; } const player = makeCar(0xe8823a); - [Obj 1, 8] Add the parked cars, the green bay and the arrow marker.
newBay()picks a free bay and fills most of the others.// ---------- parked cars and the target bay ---------- const parkedCars = []; const bay = new THREE.Mesh(new THREE.PlaneGeometry(3.2, 4.6), new THREE.MeshBasicMaterial({ color: 0x22d36a, transparent: true, opacity: 0.45 })); bay.rotation.x = -Math.PI / 2; bay.position.y = 0.02; scene.add(bay); const marker = new THREE.Mesh(new THREE.ConeGeometry(0.6, 1.2, 4), // an arrow over the free bay new THREE.MeshStandardMaterial({ color: 0x22d36a, emissive: 0x0a5a2a })); marker.rotation.x = Math.PI; // point down scene.add(marker); function newBay() { parkedCars.forEach(function (c) { scene.remove(c); }); parkedCars.length = 0; const row = ROWS[Math.floor(Math.random() * ROWS.length)]; const free = BAY_X[Math.floor(Math.random() * BAY_X.length)]; bay.position.x = free; bay.position.z = row; BAY_X.forEach(function (x) { // fill most other bays in that row if (x === free || Math.random() < 0.3) return; if (Math.hypot(x - player.position.x, row - player.position.z) < 3) return; // never on top of the player const c = makeCar([0x2563eb, 0xd9534f, 0xeeeeee, 0x12854f][Math.floor(Math.random() * 4)]); c.position.set(x, 0, row); c.rotation.y = Math.random() < 0.5 ? 0 : Math.PI; parkedCars.push(c); }); } - [Obj 2] Add the keyboard key-state object.
// ---------- keyboard ---------- const keys = {}; window.addEventListener("keydown", function (e) { keys[e.code] = true; if (e.code.startsWith("Arrow")) e.preventDefault(); if (e.code === "Enter" && state !== "playing") startGame(); }); window.addEventListener("keyup", function (e) { keys[e.code] = false; }); - [Obj 3, 4] Add
drive(): keys change the speed, steering changes the angle, and sin / cos move the car the way it faces.// ---------- driving ---------- const MAX_SPEED = 12; // units per second const ACCEL = 10; const TURN = 2.2; // radians per second at full speed let speed = 0; function drive(dt) { const up = keys.ArrowUp || keys.KeyW; const down = keys.ArrowDown || keys.KeyS; const left = keys.ArrowLeft || keys.KeyA; const right = keys.ArrowRight || keys.KeyD; if (up) speed += ACCEL * dt; if (down) speed -= ACCEL * dt; if (!up && !down) speed *= 1 - 2 * dt; // friction slows the car speed = THREE.MathUtils.clamp(speed, -MAX_SPEED / 2, MAX_SPEED); // steer only while moving, more at higher speed const steer = (left ? 1 : 0) - (right ? 1 : 0); player.rotation.y += steer * TURN * dt * (speed / MAX_SPEED); // move forward in the direction the car faces const angle = player.rotation.y; player.position.x += Math.sin(angle) * speed * dt; player.position.z += Math.cos(angle) * speed * dt; } - [Obj 5, 7] Add
collide(): clamp to the car park, and push the car back out of any parked car it touches.// ---------- staying in the car park and bumping into cars ---------- let bumpCooldown = 0; // seconds until a bump can cost time again function collide(dt) { player.position.x = THREE.MathUtils.clamp(player.position.x, -LOT, LOT); player.position.z = THREE.MathUtils.clamp(player.position.z, -LOT, LOT); bumpCooldown -= dt; parkedCars.forEach(function (c) { if (player.position.distanceTo(c.position) < 2.4) { // too close: bump const away = player.position.clone().sub(c.position).setY(0).normalize(); player.position.copy(c.position).add(away.multiplyScalar(2.4)); // push back out speed = -speed * 0.3; if (bumpCooldown <= 0) { timeLeft -= 2; // a bump costs two seconds bumpCooldown = 1; } } }); } - [Obj 5, 6] Add the chase camera.
// ---------- chase camera ---------- 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); // behind and above const wanted = player.position.clone().add(camOffset); camera.position.lerp(wanted, 1 - Math.exp(-4 * dt)); // glide towards it lookAt.copy(player.position).add(new THREE.Vector3(0, 1, 0)); camera.lookAt(lookAt); } - [Obj 8] Add
checkParked(): inside the bay, lined up, nearly stopped, for one second.// ---------- parked? inside the bay, lined up, and stopped ---------- let holdTime = 0; function checkParked(dt) { const dx = Math.abs(player.position.x - bay.position.x); const dz = Math.abs(player.position.z - bay.position.z); const lined = Math.abs(Math.sin(player.rotation.y)) < 0.2; // facing along z, either way const inside = dx < 0.6 && dz < 0.9 && lined && Math.abs(speed) < 0.5; bay.material.color.set(inside ? 0xffd34d : 0x22d36a); holdTime = inside ? holdTime + dt : 0; if (holdTime > 1) { // stay still for one second parked++; parkedEl.textContent = parked; holdTime = 0; newBay(); } } - [Obj 3, 8] Add the game state, then the animation loop, the resize handler and the start-up lines.
// ---------- game state ---------- let state = "ready"; let parked = 0; let timeLeft = 90; const parkedEl = document.getElementById("parked"); const timeEl = document.getElementById("time"); const speedEl = document.getElementById("speed"); const msgEl = document.getElementById("msg"); function startGame() { player.position.set(0, 0, 0); player.rotation.y = 0; speed = 0; parked = 0; timeLeft = 90; parkedEl.textContent = 0; msgEl.innerHTML = ""; newBay(); state = "playing"; } // ---------- animation loop ---------- const clock = new THREE.Clock(); renderer.setAnimationLoop(function () { const dt = Math.min(clock.getDelta(), 0.1); if (state === "playing") { drive(dt); collide(dt); checkParked(dt); timeLeft -= dt; timeEl.textContent = Math.max(0, Math.ceil(timeLeft)); speedEl.textContent = Math.round(Math.abs(speed) * 3.6); // pretend km/h if (timeLeft <= 0) { state = "over"; msgEl.innerHTML = "Time! You parked " + parked + " times.<br>Press Enter to play again"; } } marker.position.set(bay.position.x, 3 + Math.sin(clock.elapsedTime * 3) * 0.4, bay.position.z); marker.rotation.y += dt; followCamera(dt); renderer.render(scene, camera); }); window.addEventListener("resize", function () { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); }); newBay(); camera.position.set(0, 5, -9); - Save, press Enter and park. Check the console (F12) for errors.
- Create
📝 Tasks for this file:
Click the game, press Enter, then drive with the arrow keys or WASD. Stop inside the green bay, lined up with the white lines.
📚 Useful Vector3 methods
v.set(x, y, z)— change all three values.v.copy(w)— make v equal to w.v.clone()— a new copy, so changing it does not change v.v.add(w)/v.sub(w)— change v by adding or subtracting w (v itself changes!).v.normalize()— keep the direction, make the length 1.v.multiplyScalar(k)— make it k times longer.v.lerp(w, a)— move v a fraction a of the way to w.v.distanceTo(w)— the distance.