TExcelTAD
Home › 3D Web Games with Three.js › Explorer 1: World & Character

Explorer 1: World & Character

Time to put the course together in one game. Over four lessons we build Crystal Meadow, a small 3D exploration game in the spirit of the "first 3D game" every engine tutorial ends with: a walled meadow with trees, rocks, ruins and three plateaus; a little explorer you steer with the keyboard; six glowing crystals hidden around the map; and a portal in the middle that opens once you have them all. Step by step:

Lesson Adds
1. World & Character (this one) the level built from primitives, lights and shadows, a character with a walk cycle, a follow camera
2. Follow Camera & Collision Rapier physics: a character controller with collisions, steps, slopes and jumping; an orbit camera that avoids walls
3. Collectibles & Objective crystals as sensors, a HUD, the portal, winning
4. Menu, Pause & Sound title, pause and win screens, synthesized sound effects, saving the best time

Every step is a complete, playable program. It's long for a playground (about 230 lines here, 450 at the end), so read it section by section; each section is marked with a // ---------- … ---------- comment.

What this step contains

The world is built entirely from Three.js primitives, with a seeded random generator (mulberry32(2024)) so the trees and rocks land in the same places every time you run it, and so the crystals placed later never end up inside a tree:

  • a 60 × 60 m ground plane and a low stone wall around it;
  • three plateaus: one with stairs, one with a ramp, and one you'll have to jump onto in the next lesson;
  • four ruined walls around the centre, where the portal will stand;
  • 34 trees (a cylinder trunk and a cone of leaves, flatShading for the low-poly look) and 14 rocks (IcosahedronGeometry with detail 0), placed by freeSpot(), which rejects positions near the important places.

All scenery goes through one helper, solid(mesh). Right now it only adds the mesh with shadows enabled; in the next lesson the same function also creates the matching physics collider, which is why every piece of scenery is created through it.

Lighting is the outdoor recipe from Lights: a hemisphere light for sky and ground bounce, and one directional "sun" that casts shadows. The sun's shadow box is only 28 m wide, so it follows the hero every frame (light and target move together, see Shadows), keeping shadows sharp wherever you walk. scene.fog fades the far side of the meadow into the sky color.

The hero is a Group built from primitives: capsule torso, sphere head, a backpack, and four limbs. Each limb is a box hanging from a pivot group at the shoulder or hip (the box is offset down by half its length), so rotating the pivot swings the limb like a pendulum. The walk cycle is one sine wave: legs swing in opposite phase, arms opposite to the legs, scaled by how fast the hero is moving, so the limbs come to rest when you stop.

js
walkPhase += speedFactor * dt * 11;              // advance the cycle only while moving
const swing = Math.sin(walkPhase) * 0.7 * speedFactor;
legL.rotation.x = swing;  legR.rotation.x = -swing;
armL.rotation.x = -swing * 0.8;  armR.rotation.x = swing * 0.8;

Movement reads WASD/arrows, normalizes diagonals, and turns the hero smoothly toward the direction of travel with atan2 and a wrapped angle difference (the shortest way around). The camera sits at a fixed offset behind and above the hero and follows with frame-rate-independent damping (1 - Math.exp(-5 * dt), see Third-Person Camera).

Play it

html · try it yourself
<style>
  html, body { margin: 0; height: 100%; overflow: hidden; background: #0e1018; }
  canvas { display: block; outline: none; touch-action: none; }
  #hud { position: fixed; left: 10px; top: 8px; color: #fff; font: 13px system-ui, sans-serif; pointer-events: none; text-shadow: 0 1px 2px #000; }
  #veil { position: fixed; inset: 0; display: grid; place-content: center; background: rgba(0, 0, 0, 0.55); color: #fff; font: 600 20px system-ui, sans-serif; text-align: center; pointer-events: none; }
  #veil small { display: block; margin-top: 6px; font-weight: 400; font-size: 13px; }
  #veil.off { display: none; }
</style>
<div id="hud"></div>
<div id="veil">Click to play<small>WASD or arrows to walk</small></div>
<script type="module">
import * as THREE from 'three';

// ---- 3D play kit: renderer, click to focus, keys, pause on blur, fixed-step loop ----
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.prepend(renderer.domElement);
const cv = renderer.domElement, veil = document.getElementById('veil');
const keys = new Set(), pressed = new Set();   // held now / pressed since the last update
let active = false, drawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; veil.classList.add('off'); });
cv.addEventListener('blur', () => { active = false; drawn = false; veil.classList.remove('off'); keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
  if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault();   // don't scroll the lesson
  if (!e.repeat) pressed.add(e.code);
  keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function run(scene, camera, update) {
  const STEP = 1 / 60, timer = new THREE.Timer();
  let acc = 0;
  addEventListener('resize', () => {
    camera.aspect = innerWidth / innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(innerWidth, innerHeight);
    drawn = false;
  });
  renderer.setAnimationLoop((t) => {
    timer.update(t);
    if (active) {
      acc += Math.min(timer.getDelta(), 0.1);
      while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
    } else if (drawn) return;          // paused: the last frame stays on screen
    renderer.render(scene, camera);
    drawn = true;
  });
}
// ---- end of play kit ----

// ---------- seeded random numbers ----------
function mulberry32(seed) {
  return () => {
    seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
    let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
  };
}
const rng = mulberry32(2024);

// ---------- scene, lights ----------
renderer.shadowMap.enabled = true;
const scene = new THREE.Scene();
scene.background = new THREE.Color('#9fc6ea');
scene.fog = new THREE.Fog('#9fc6ea', 25, 70);
const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 150);
scene.add(new THREE.HemisphereLight('#e4f0ff', '#58704a', 1.4));
const sun = new THREE.DirectionalLight('#fff3dd', 2.4);
sun.castShadow = true;
sun.shadow.mapSize.set(1024, 1024);
Object.assign(sun.shadow.camera, { left: -14, right: 14, top: 14, bottom: -14, near: 1, far: 60 });
sun.shadow.normalBias = 0.03;
scene.add(sun, sun.target);
const SUN_OFFSET = new THREE.Vector3(-12, 20, 8);

function solid(mesh) {                             // add a static piece of scenery
  mesh.castShadow = mesh.receiveShadow = true;
  scene.add(mesh);
}

// ---------- the world ----------
const HALF = 30;                                   // the meadow spans -30..30
const ground = new THREE.Mesh(new THREE.PlaneGeometry(HALF * 2, HALF * 2), new THREE.MeshStandardMaterial({ color: '#6f9e58' }));
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
const stone = new THREE.MeshStandardMaterial({ color: '#a39a8a', roughness: 0.9 });
for (const [x, z, w, d] of [[0, -HALF, HALF * 2, 1], [0, HALF, HALF * 2, 1], [-HALF, 0, 1, HALF * 2], [HALF, 0, 1, HALF * 2]]) {
  const wall = new THREE.Mesh(new THREE.BoxGeometry(w, 1, d), stone);
  wall.position.set(x, 0.5, z);
  solid(wall);
}

// Plateaus: one with stairs, one with a ramp, one you must jump onto.
const rock = new THREE.MeshStandardMaterial({ color: '#8d8577', roughness: 0.95 });
function box(w, h, d, x, y, z, mat, rotX = 0) {
  const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), mat);
  m.position.set(x, y, z);
  m.rotation.x = rotX;
  solid(m);
  return m;
}
box(6, 1.6, 6, -16, 0.8, -14, rock);                                   // plateau A, top 1.6
for (let i = 0; i < 4; i++) box(2, 0.4 * (i + 1), 1, -16, 0.2 * (i + 1), -8.5 - i, rock);   // its stairs
box(6, 2.4, 6, 16, 1.2, -14, rock);                                    // plateau B, top 2.4
box(2.5, 0.3, 7, 16, 1.15, -7.6, rock, 0.37);                           // its ramp (~21°)
box(4, 1.1, 4, 15, 0.55, 14, rock);                                    // plateau C, top 1.1: jump

// Ruins around the shrine.
for (const [x, z, w, d] of [[-5, -5, 4, 0.6], [5, -5, 4, 0.6], [-5, 5, 0.6, 4], [5, 5, 0.6, 3]]) box(w, 1.8, d, x, 0.9, z, stone);

// Trees and rocks, scattered with the seeded RNG, away from the important places.
const keepClear = [[0, 0, 8], [-16, -12, 6], [16, -11, 6], [15, 14, 4]];
function freeSpot(margin) {
  for (;;) {
    const x = (rng() * 2 - 1) * (HALF - 3), z = (rng() * 2 - 1) * (HALF - 3);
    if (keepClear.every(([cx, cz, r]) => Math.hypot(x - cx, z - cz) > r + margin)) return [x, z];
  }
}
const trunkGeo = new THREE.CylinderGeometry(0.2, 0.3, 1.6, 8);
const leafGeo = new THREE.ConeGeometry(1.3, 3, 8);
const trunkMat = new THREE.MeshStandardMaterial({ color: '#6b4a2b' });
const leafMat = new THREE.MeshStandardMaterial({ color: '#2f6e3a', flatShading: true });
for (let i = 0; i < 34; i++) {
  const [x, z] = freeSpot(1.5);
  const s = 0.8 + rng() * 0.6;
  const trunk = new THREE.Mesh(trunkGeo, trunkMat);
  trunk.position.set(x, 0.8 * s, z);
  trunk.scale.setScalar(s);
  const leaves = new THREE.Mesh(leafGeo, leafMat);
  leaves.position.set(x, (1.6 + 1.3) * s, z);
  leaves.scale.setScalar(s);
  leaves.castShadow = true;
  scene.add(leaves);
  solid(trunk);
}
const rockGeo = new THREE.IcosahedronGeometry(1, 0);
for (let i = 0; i < 14; i++) {
  const [x, z] = freeSpot(1.5);
  const r = 0.5 + rng() * 0.8;
  const m = new THREE.Mesh(rockGeo, rock);
  m.position.set(x, r * 0.5, z);
  m.scale.setScalar(r);
  m.rotation.set(rng() * 3, rng() * 3, 0);
  solid(m);
}

// ---------- the hero: a little explorer built from primitives ----------
const hero = new THREE.Group();
const skin = new THREE.MeshStandardMaterial({ color: '#f1c27d' });
const cloth = new THREE.MeshStandardMaterial({ color: '#e86a3a' });
const dark = new THREE.MeshStandardMaterial({ color: '#3b3f4a' });
const torso = new THREE.Mesh(new THREE.CapsuleGeometry(0.28, 0.45, 4, 12), cloth);
torso.position.y = 1.0;
const head = new THREE.Mesh(new THREE.SphereGeometry(0.22, 16, 12), skin);
head.position.y = 1.55;
const pack = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.45, 0.2), dark);
pack.position.set(0, 1.05, -0.3);
function limb(w, h, x, y, mat) {                    // a box hanging from a pivot at its top
  const pivot = new THREE.Group();
  pivot.position.set(x, y, 0);
  const m = new THREE.Mesh(new THREE.BoxGeometry(w, h, w), mat);
  m.position.y = -h / 2;
  m.castShadow = true;
  pivot.add(m);
  hero.add(pivot);
  return pivot;
}
const legL = limb(0.16, 0.6, -0.13, 0.62, dark), legR = limb(0.16, 0.6, 0.13, 0.62, dark);
const armL = limb(0.12, 0.5, -0.38, 1.3, cloth), armR = limb(0.12, 0.5, 0.38, 1.3, cloth);
for (const m of [torso, head, pack]) m.castShadow = true;
hero.add(torso, head, pack);
scene.add(hero);

const START = new THREE.Vector3(0, 0, 9);
hero.position.copy(START);

// ---------- camera: a fixed offset behind the hero, smoothed ----------
const CAM_OFFSET = new THREE.Vector3(0, 4.5, 7.5);
const lookAt = new THREE.Vector3(), camWanted = new THREE.Vector3();
function updateCamera(dt, snap = false) {
  lookAt.set(hero.position.x, hero.position.y + 1.2, hero.position.z);
  camWanted.copy(hero.position).add(CAM_OFFSET);
  if (snap) camera.position.copy(camWanted);
  else camera.position.lerp(camWanted, 1 - Math.exp(-5 * dt));   // frame-rate independent smoothing
  camera.lookAt(lookAt);
}

// ---------- state ----------
const hud = document.getElementById('hud');
let heroYaw = 0, walkPhase = 0;

// ---------- the update ----------
const SPEED = 5.5;
run(scene, camera, (dt) => {
  // Input: WASD on the ground plane (the camera never turns in this step, so -Z is "forward").
  let mx = (keys.has('KeyD') || keys.has('ArrowRight') ? 1 : 0) - (keys.has('KeyA') || keys.has('ArrowLeft') ? 1 : 0);
  let mz = (keys.has('KeyS') || keys.has('ArrowDown') ? 1 : 0) - (keys.has('KeyW') || keys.has('ArrowUp') ? 1 : 0);
  const len = Math.hypot(mx, mz);
  if (len > 1) { mx /= len; mz /= len; }
  hero.position.x = THREE.MathUtils.clamp(hero.position.x + mx * SPEED * dt, -29, 29);   // no collisions yet:
  hero.position.z = THREE.MathUtils.clamp(hero.position.z + mz * SPEED * dt, -29, 29);   // walk through anything

  // Visuals: facing and walk cycle.
  if (len > 0.01) {
    let diff = Math.atan2(mx, mz) - heroYaw;
    diff = Math.atan2(Math.sin(diff), Math.cos(diff));
    heroYaw += diff * (1 - Math.exp(-14 * dt));
    hero.rotation.y = heroYaw;
  }
  walkPhase += Math.min(len, 1) * dt * 11;
  const swing = Math.sin(walkPhase) * 0.7 * Math.min(len, 1);
  legL.rotation.x = swing; legR.rotation.x = -swing;
  armL.rotation.x = -swing * 0.8; armR.rotation.x = swing * 0.8;

  sun.target.position.copy(hero.position);
  sun.position.copy(hero.position).add(SUN_OFFSET);
  updateCamera(dt);
  hud.textContent = `x ${hero.position.x.toFixed(1)}  z ${hero.position.z.toFixed(1)}`;
});

// First frame: place everything.
sun.target.position.copy(hero.position);
sun.position.copy(hero.position).add(SUN_OFFSET);
updateCamera(0, true);
</script>

Walk around and notice what's missing, because that's the next lesson: you walk straight through trees, rocks and walls, the plateaus are just boxes you pass through, there is no jumping, and when a tree is between the camera and the hero, you lose sight of the hero.

Why build the level from code?

For a real game you'd model the level in Blender and load it as glTF (glTF & GLTFLoader), with empties marking where the crystals and the player start go. Building it from code here keeps the example self-contained, and it mirrors how that pipeline works anyway: a list of objects with transforms, a collider for each solid one, and named markers for gameplay. When you switch to a glTF level, solid() becomes a traverse over the loaded scene that creates colliders for meshes with a naming convention (*_col), and CRYSTAL_SPOTS becomes a list read from the markers.

Things to try

  • Change the seed in mulberry32(2024) for a different forest.
  • Make the hero run while Shift is held (raise SPEED and the walk-cycle rate together, or the feet slide).
  • Add a gentle bob to the torso: torso.position.y = 1.0 + Math.abs(Math.sin(walkPhase)) * 0.04.
  • Replace the trees with an InstancedMesh for trunks and one for leaves (InstancedMesh & BatchedMesh): 68 draw calls become 2.

Test yourself

Why is each limb a box inside a pivot group instead of a rotated box?

  1. Groups render faster
  2. So the limb rotates around the shoulder or hip (the pivot) instead of around its own centre
  3. Boxes can't be rotated
  4. To share materials

Why does the sun's shadow box follow the hero?

  1. Directional lights must be near the camera
  2. A small box keeps shadow texels small (sharp shadows); moving it keeps the area around the hero covered
  3. To make the sun rise and set
  4. Shadows only work at the origin

Why does the level use a seeded random generator to place trees?

  1. Math.random is slower
  2. So the layout is identical every run, which keeps level design, bug reports and later crystal placement reliable
  3. Seeded generators make better forests
  4. WebGL requires it