Web Games Development · Movement & cameras · ~150 minutes
THREE.Group.Math.sin and Math.cos.Vector3 methods: clone, add, sub, normalize, copy.lerp and lookAt.Set up a Week9 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.
Week9\
Week9, open it in VS Code, and open the terminal with Ctrl+`.npm init -y
npm install three@0.170.0
npm install --save-dev vite@5
package.json from Materials for this week into the folder, then run npm install instead.http://localhost:5173/car.html. Press Ctrl+C in the terminal to stop it.
npx vite
package.json and node_modules, and npx vite shows Local: http://localhost:5173/.Week9\car.html
car.html and 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>
npx vite running, open http://localhost:5173/car.html. You should see the car group turning, wheels spinning inside it.BoxGeometry(1.8, 0.1, 0.5) at (0, 1.2, -1.7), added to the car group.Week9\speedDemo.html
speedDemo.html and 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>
npx vite running, open http://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.ACCEL to 25: how does it feel?1 - 0.5 * dt.MAX_SPEED to 20.Week9\steerDemo.html
steerDemo.html and 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>
npx vite running, open http://localhost:5173/steerDemo.html. You should see a car you can drive and steer, leaving a trail, with an arrow pointing forward.* (speed / MAX_SPEED) from the steering line and drive.TURN to 4 for tighter turns.Week9\chaseCamera.html
chaseCamera.html and 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>
npx vite running, open http://localhost:5173/chaseCamera.html. You should see the camera chasing a car round a figure of eight.camOffset.set(…) to 15 and 10.Math.exp(-4 * dt) to 1, then 20.t += dt * 1.Week9\parkIt.html
parkIt.html with 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>
HemisphereLight plus 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);
// ---------- 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);
}
});
makeCar(). Every part is added to a Group, 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);
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);
});
}
// ---------- 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; });
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;
}
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;
}
}
});
}
// ---------- 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);
}
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();
}
}
// ---------- 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);
| Criterion | Points | Score |
|---|---|---|
| Car built as a Group of meshes | 2 | |
| Speed, acceleration, friction and limits | 3 | |
| Steering with sin / cos | 3 | |
| Chase camera with lerp and lookAt | 3 | |
| Bounds, bumps and parking check | 3 | |
| Runs with no console errors | 1 | |
| Total | 15 |
add() on player.position directly, which moves the car.sin and cos, so the car drives sideways.camera.position directly instead of using lerp.e.preventDefault(), so the arrow keys scroll the page.Progress and quiz scores are also tracked on the Week 9 lab page in the class website.