Owns the Three.js r160+ layer of a browser 3D game: scene graph, glTF with DRACO/KTX2, animation, Rapier or cannon-es, EffectComposer, dispose, and Vite. Use when starting or fixing a vanilla Three.js/WebGL web game (r3f only if asked). Not for the HTML5 game shell (browser-game-architecture), cross-engine FPS diagnosis (webgl-performance-tuning), Godot/Unity, or 2D Canvas/Pixi.
Own the Three.js-specific layer of a browser 3D game: renderer and scene-graph setup, the game loop, the glTF asset pipeline, input, physics integration, animation, postprocessing, memory discipline, and the Vite toolchain that ships it. Engine-agnostic design theory and the surrounding web-app shell belong to sibling skills — this skill makes the Three.js part correct, fast, and leak-free.
When to Use
Starting a new browser 3D game with vanilla Three.js (Vite + TypeScript scaffold)
Structuring the game loop: fixed-timestep simulation, render interpolation, pause/timescale, tab-away safety
Production builds with Vite: decoder files, base paths, code splitting, compression
Adding a light WebXR mode to an existing Three.js game
Trigger keywords: three.js, threejs, webgl game, web game 3d, gltf, EffectComposer, Rapier three, Vite three, setAnimationLoop, InstancedMesh, BatchedMesh, WebGPURenderer, r3f, react-three-fiber.
Do not use
Offline / film rendering (Blender Cycles, path tracers) — out of scope entirely
React apps: only reach for @react-three/fiber if the user explicitly asks for React — see "React (r3f) policy" below. Default is vanilla Three.js
2D-only games — Canvas2D/Pixi territory; Three.js is overkill
Godot / Unity / native engines — use the godot-* and engine-specific skills
Pure shader authoring / VFX deep-dives — game-technical-art-vfx
Generic web-app concerns (routing, auth, backend) — not a game skill problem
Bundled references — load on demand
Do not paste these wholesale into context. Load the specific file when the task demands it:
File
Load when…
reference.md
You need API details: renderer options, color management, cameras, lights/shadows, materials, geometry, instancing, textures, loaders, animation system, raycasting, postprocessing, audio, timing, dispose semantics, artifacts/gotchas, debugging toolkit
architecture.md
You are structuring the codebase: Game class, fixed-timestep loop, state machine, entities/systems, event bus, input action mapping, physics sync, asset manager, level lifecycle, pooling, TypeScript patterns
recipes.md
You need copy-paste code: Vite+TS scaffold, renderer + resize, loop class, loader stack, Rapier character controller, touch joystick, gamepad, bloom composer, pooling, deep-dispose, debug rig, production build
examples.md
You need a worked end-to-end reference: complete minimal game, animated glTF character with state machine, Rapier physics playground, mobile endless-runner skeleton
This skill owns the Three.js implementation of those concerns; siblings own the engine-agnostic theory.
Prerequisites
Node.js 18+ and npm
A modern browser with WebGL 2 support (Chrome/Edge/Firefox/Safari)
Three.js r160 or newer installed (npm i three)
TypeScript types (npm i -D @types/three)
Vite as the dev server / bundler (npm create vite@latest)
Windows host is primary. Use PowerShell for all CLI commands. Path separators in examples use / for cross-tool compatibility, but Windows backslash \ is equally valid in PowerShell.
Version contract (r160+, assume ~r165)
Write and expect modern API. When copying code from old tutorials, rewrite these red flags on sight:
Legacy (pre-r152/r155)
Modern (r160+)
import X from 'three/examples/jsm/...'
import X from 'three/addons/...'
renderer.outputEncoding = THREE.sRGBEncoding
renderer.outputColorSpace = THREE.SRGBColorSpace (already the default)
texture.encoding = THREE.sRGBEncoding
texture.colorSpace = THREE.SRGBColorSpace
renderer.physicallyCorrectLights = true
Default behavior; useLegacyLights is removed (r165)
renderer.gammaOutput / gammaFactor
Gone — color management handles it
THREE.Geometry
THREE.BufferGeometry only
GammaCorrectionShader at end of composer
OutputPass (r154+)
Other r160+ facts to rely on:
Color/albedo/emissive textures need texture.colorSpace = THREE.SRGBColorSpace; normal/roughness/metalness/AO/data textures stay linear (NoColorSpace). GLTFLoader sets this correctly for you.
BatchedMesh (r159+) batches different geometries sharing one material into one draw call; InstancedMesh repeats one geometry.
renderer.setAnimationLoop(fn) is the canonical loop driver (required for WebXR; equivalent to rAF otherwise).
WebGPURenderer + TSL node materials exist and are maturing; target WebGLRenderer for shipping games, note WebGPU as forward-looking only.
Procedure
1. Scaffold the project
npm create vite@latest my-game -- --template vanilla-ts
cd my-game
npm i three
npm i -D @types/three
npm i @dimforge/rapier3d-compat # only if physics chosen (see table below)
For the full scaffold (index.html, CSS, vite.config, entry, resize handling) load recipes.md.
Canonical pattern — fixed-timestep simulation with clamped frame delta and render-side interpolation:
const FIXED_DT = 1 / 60;
const MAX_FRAME = 0.25; // tab-away / breakpoint guard
let accumulator = 0;
let last = performance.now();
renderer.setAnimationLoop(() => {
const now = performance.now();
const frame = Math.min((now - last) / 1000, MAX_FRAME);
last = now;
accumulator += frame;
input.poll(); // one snapshot per frame
while (accumulator >= FIXED_DT) {
simulate(FIXED_DT); // gameplay + physics.step(FIXED_DT)
accumulator -= FIXED_DT;
}
const alpha = accumulator / FIXED_DT;
syncVisuals(alpha); // interpolate body → mesh transforms
updatePresentation(frame); // mixers, camera damp, particles, HUD
renderer.render(scene, camera); // or composer.render()
});
Loop rules:
Never step physics with a variable dt.
Clamp the frame delta or a background tab will explode the simulation on return.
Call clock.getDelta() at most once per frame (better: own the timing as above).
Pause = stop accumulating, keep rendering.
Full loop class with timescale and visibilitychange handling → load recipes.md. Where the loop lives in the codebase → load architecture.md.
4. Set up the asset pipeline (glTF-first)
One format: .glb (binary glTF). It carries meshes, PBR materials, skins, morphs, and animations. FBX/OBJ only as intermediate DCC formats — convert before shipping. Authoring rules → game-assets-pipeline.
Compression: Draco (smallest geometry, one-time decode cost) or Meshopt (near-Draco size, much faster decode, also compresses animation) — prefer Meshopt via gltf-transform optimize. Textures: KTX2/Basis (stays compressed on GPU — the only fix for texture memory, not just download size).
Decoders:DRACOLoader and KTX2Loader need their decoder/transcoder folders copied into public/ (from node_modules/three/examples/jsm/libs/). MeshoptDecoder is a pure JS/WASM module import. Wiring recipe → recipes.md.
Preload via a typed manifest before gameplay; show progress from LoadingManager. Loading mid-gameplay causes hitches (decode + GPU upload). Warm shaders with renderer.compileAsync(scene, camera) after load.
Never .clone() a skinned mesh — use SkeletonUtils.clone() (three/addons/utils/SkeletonUtils.js).
Cache by URL; share geometries/materials across instances; refcount before disposing shared assets (see Memory rules below).
5. Choose and wire collision / physics
Situation
Choice
Puzzle/menu-driven, no dynamics
No physics. Transforms + MathUtils + distance checks
Character vs static level, picking, hitscan
three-mesh-bvh — BVH-accelerated raycast/shapecast against level geometry; write your own kinematics
Rigid-body dynamics, stacks, joints, robust character controller
Rapier (@dimforge/rapier3d-compat) — fast WASM, ships a KinematicCharacterController (slopes, steps, snap-to-ground). Default for real physics
Tiny bundle, simple dynamics, WASM disallowed
cannon-es — pure JS, easy API, slower, weaker trimesh support
Legacy ammo.js codebase
Maintain only; don't start new projects on it
Integration rules:
The physics world steps inside the fixed update with FIXED_DT.
Copy body transforms to meshes after stepping (physics owns dynamic transforms — never write mesh positions back except for kinematic bodies).
Build colliders from simplified shapes (capsule/box/hull), not render meshes.
Never scale a mesh to "resize" its collider.
Sync architecture → load architecture.md. Full Rapier setup + character controller → load recipes.md.
6. Wire input
Use Pointer Events (pointerdown/move/up + setPointerCapture) — one code path for mouse, touch, and pen. Never mix in mousedown/touchstart handlers alongside.
Abstract device → action map (moveX/moveY/jump/fire), then gameplay reads a per-frame snapshot. Enables rebinding, gamepad, touch, and replays without touching game code. Pattern → load architecture.md.
Gamepad API is poll-based: read navigator.getGamepads() once per frame inside input.poll(); apply a dead zone (~0.15).
Keyboard: track event.code (layout-independent) in a Set; ignore repeats; clear the set on blur.
Pointer lock (canvas.requestPointerLock()) for FPS-style mouselook; must be called from a user gesture; listen for pointerlockchange to pause on Esc.
7. Mobile pass
touch-action: none on the canvas CSS or the browser will scroll/zoom instead of sending you pointermoves.
Clamp DPR to 1.5–2; expose a render-scale setting (renderer.setPixelRatio is your cheapest quality knob).
Virtual joystick = two pointer regions (left stick, right look) tracked by pointerId — hand-rolled recipe in recipes.md; multi-touch means you must track pointers by id, never "the" pointer.
Budgets drop hard: ≤100–150 draw calls, ≤300k triangles, one shadow-casting light or baked/blob shadows, skip postprocessing on low-end.
Verify with renderer.info.memory (geometries/textures counts) — it must return to baseline after a load→unload cycle. If it climbs, you leak.
Full app teardown (SPA route change): also renderer.dispose(), renderer.forceContextLoss(), drop the canvas.
Per-frame allocations are the other memory sin: no new Vector3() / .clone() in the loop — hoist scratch temps to module scope and .copy() into them.
10. Production build with Vite
Ensure decoder files (DRACO, KTX2) are in public/ and referenced by absolute path.
Set base in vite.config.ts if the game is served from a subpath.
Use code splitting for large assets or optional modes (e.g., WebXR).
Enable compression plugins (vite-plugin-compression for gzip/brotli).
Run npm run build and verify the output serves correctly from the target path.
Full production build config → load recipes.md.
11. WebXR (light mode, if requested)
renderer.xr.enabled = true, add VRButton/XRButton from three/addons/webxr/.
Drive everything through renderer.setAnimationLoop (rAF does not fire in XR sessions).
Per-eye rendering roughly doubles GPU cost: drop postprocessing first, keep DPR at 1, use renderer.xr.setFramebufferScaleFactor to trade sharpness for frame rate.
Controllers via renderer.xr.getController(i) with select events.
Treat XR as a bonus mode, not the primary target, unless the user says otherwise.
Scene graph rules that prevent 80% of beginner bugs:
An Object3D's position/quaternion/scale are local to its parent. World transform lives in matrixWorld, updated during render (or via updateWorldMatrix(true, false) when you need it mid-frame).
parent.add(child) re-parents and changes world position unless you use parent.attach(child) (keeps world transform).
Nothing renders without: a camera in a sane position, a light (for lit materials), and geometry with a material. Debug "black screen" in that order.
One renderer, one canvas, one loop. Multiple scenes/cameras are fine (HUD pass, minimap) — multiple renderers are not.
Performance budgets & triage
Symptom
First suspects
High CPU, low GPU
Draw calls (renderer.info.render.calls), per-frame allocation/GC, matrix updates on thousands of static objects (matrixAutoUpdate = false), unbatched raycasting
High GPU, frame drops at high DPR
Fill rate/overdraw (transparent layers, post passes), shadow map size, DPR unclamped
Default answer is vanilla Three.js. Only if the user explicitly wants React, switch to @react-three/fiber + drei and keep the paradigm pure — never drive a vanilla imperative scene from React state per frame, and never setState inside useFrame. Concept mapping when translating:
Vanilla
r3f
scene.add(mesh)
JSX: <mesh> declares graph; unmount auto-disposes
renderer.setAnimationLoop
useFrame((state, delta) => ...) with useRef mutation
Manual loaders + cache
useGLTF / useLoader (suspense, cached)
Manual resize
<Canvas> handles it
This skill's loop/physics/memory rules
Still apply — fixed step via accumulator inside useFrame, @react-three/rapier for physics
Pitfalls
new Vector3/Quaternion/Matrix4 (or .clone()) inside the loop — GC churn; hoist scratch objects.
Per-entity new Material()/new Geometry() for identical entities — share and instance.
Stepping physics with variable frame dt — non-deterministic, explodes on hitches.
Unclamped setPixelRatio(devicePixelRatio) — a DPR-3 phone renders 9× the pixels.
Removing meshes without disposing (leak), or disposing shared assets in use (breakage) — refcount.
Loading assets on demand mid-gameplay — preload via manifest; hitches are a design failure.
Raycasting the whole scene recursively every frame — target lists, layers, or three-mesh-bvh.
clock.getDelta() called from multiple places — each call resets it; own timing centrally.
No frame-delta clamp — returning from a background tab teleports/explodes everything.
transparent: true everywhere — overdraw + sort popping; use alphaTest for cutouts.
Shadow maps on every light / 4096 maps by default — one sun-shadow + cheats first.
Updating DOM HUD (innerText, styles) every frame unconditionally — write on change only.
Copy-pasting pre-r152 tutorial code without applying the Version-contract table above.
scene.traverse() per frame to find objects — cache references at spawn time.
matrixAutoUpdate left on for thousands of static objects.
Sequential await load(); await load(); — Promise.all the manifest.
Mixing r3f and vanilla idioms in one codebase.
Using .clone() on a skinned mesh instead of SkeletonUtils.clone() — broken skinning.
Forgetting texture.colorSpace = THREE.SRGBColorSpace for color textures loaded outside GLTFLoader.
Not handling webglcontextlost — the game silently dies on context switch.
Verification
Run through this checklist before calling a task done:
renderer.info.memory returns to baseline after a level load→unload cycle
renderer.info.render.calls within budget on the heaviest scene
60 fps with DevTools 6× CPU throttle (or explicit 30 fps mobile target held)
No per-frame allocations in the hot path (DevTools allocation sampling while idling in-game)
Touch: joystick + camera work simultaneously (multi-touch by pointerId), page doesn't scroll
Tab-away 30s → return: no physics explosion, audio muted while hidden
Production vite build served from a subpath works (decoder files, base path)
Ship gate run via web-game-release-review
Quick verification commands
# Confirm Three.js version is r160+
npm ls three
# Run the dev server
npm run dev
# Production build
npm run build
# Preview the production build
npm run preview
Expected npm ls three output:three@0.160.0 or higher.
Expected renderer.info.memory check (in console during gameplay):
console.log(renderer.info.memory); // { geometries: N, textures: M }
After a full load→unload cycle, N and M must return to their pre-load baseline. If they climb, there is a leak.
Progress checklist (working a task)
Scaffold or locate project; confirm three version ≥ r160 and Vite config (load recipes.md)
Renderer defaults + resize + DPR clamp in place
Fixed-timestep loop owns all timing; delta clamped
Physics choice made from the table and wired in the fixed step
Asset manifest preloads everything; decoders wired; skinned clones via SkeletonUtils
1---
2name: threejs-game-development
3version: 1.0.1
4description: >-
5 Owns the Three.js r160+ layer of a browser 3D game: scene graph, glTF with
6 DRACO/KTX2, animation, Rapier or cannon-es, EffectComposer, dispose, and Vite.
7 Use when starting or fixing a vanilla Three.js/WebGL web game (r3f only if
8 asked). Not for the HTML5 game shell (browser-game-architecture), cross-engine
9 FPS diagnosis (webgl-performance-tuning), Godot/Unity, or 2D Canvas/Pixi.
10risk: safe
11source: opus
12date_added: 2026-07-15
13metadata:
14 source: https://skillmd.com/skills/kayforkind/threejs-game-development
15---
1617# threejs-game-development
1819Own the Three.js-specific layer of a browser 3D game: renderer and scene-graph setup, the game loop, the glTF asset pipeline, input, physics integration, animation, postprocessing, memory discipline, and the Vite toolchain that ships it. Engine-agnostic design theory and the surrounding web-app shell belong to sibling skills — this skill makes the *Three.js* part correct, fast, and leak-free.
2021## When to Use
2223- Starting a new browser 3D game with vanilla Three.js (Vite + TypeScript scaffold)
24- Structuring the game loop: fixed-timestep simulation, render interpolation, pause/timescale, tab-away safety
25- Loading and managing assets: glTF + DRACO / KTX2 / Meshopt, preload manifests, caching, cloning skinned meshes
26- Choosing and wiring collision/physics: none vs raycast-only vs three-mesh-bvh vs Rapier vs cannon-es
27- Character movement, camera follow, animation crossfades, raycast picking
28- Touch controls and mobile-safe render settings for WebGL games
29- Postprocessing chains (EffectComposer) that survive resize and DPR changes
30- Fixing leaks, hitches, GC churn, or WebGL context loss; dispose semantics
31- Production builds with Vite: decoder files, base paths, code splitting, compression
32- Adding a light WebXR mode to an existing Three.js game
3334**Trigger keywords:** three.js, threejs, webgl game, web game 3d, gltf, EffectComposer, Rapier three, Vite three, setAnimationLoop, InstancedMesh, BatchedMesh, WebGPURenderer, r3f, react-three-fiber.
3536### Do not use
3738- **Offline / film rendering** (Blender Cycles, path tracers) — out of scope entirely
39- **React apps**: only reach for `@react-three/fiber` if the user explicitly asks for React — see "React (r3f) policy" below. Default is vanilla Three.js
40- **2D-only games** — Canvas2D/Pixi territory; Three.js is overkill
41- **Godot / Unity / native engines** — use the `godot-*` and engine-specific skills
42- **Pure shader authoring / VFX deep-dives** — `game-technical-art-vfx`
43- **Generic web-app concerns** (routing, auth, backend) — not a game skill problem
4445### Bundled references — load on demand
4647Do not paste these wholesale into context. Load the specific file when the task demands it:
4849| File | Load when… |
50|---|---|
51| `reference.md` | You need API details: renderer options, color management, cameras, lights/shadows, materials, geometry, instancing, textures, loaders, animation system, raycasting, postprocessing, audio, timing, dispose semantics, artifacts/gotchas, debugging toolkit |
52| `architecture.md` | You are structuring the codebase: Game class, fixed-timestep loop, state machine, entities/systems, event bus, input action mapping, physics sync, asset manager, level lifecycle, pooling, TypeScript patterns |
53| `recipes.md` | You need copy-paste code: Vite+TS scaffold, renderer + resize, loop class, loader stack, Rapier character controller, touch joystick, gamepad, bloom composer, pooling, deep-dispose, debug rig, production build |
54| `examples.md` | You need a worked end-to-end reference: complete minimal game, animated glTF character with state machine, Rapier physics playground, mobile endless-runner skeleton |
5556### Routing to sibling skills
5758| Need | Skill |
59|---|---|
60| Overall web-game shell: menus, saves, meta-loop, session flow | `browser-game-architecture` |
61| Lighting theory, PBR channel rules, post look-dev, quality tiers | `game-3d-rendering` |
62| DCC export, glTF authoring, texture budgets, import hygiene | `game-assets-pipeline` |
63| Camera *feel*: follow rigs, shake, framing (engine-agnostic) | `game-camera-system` |
64| Input abstraction patterns (engine-agnostic) | `game-input-handling` |
65| Profiling methodology and tooling discipline | `game-performance-profiling` |
66| Shipping: perf audit, compatibility, release checklist | `web-game-release-review` |
6768This skill owns the Three.js *implementation* of those concerns; siblings own the engine-agnostic theory.
6970## Prerequisites
7172- Node.js 18+ and npm
73- A modern browser with WebGL 2 support (Chrome/Edge/Firefox/Safari)
74- Three.js r160 or newer installed (`npm i three`)
75- TypeScript types (`npm i -D @types/three`)
76- Vite as the dev server / bundler (`npm create vite@latest`)
77- **Windows host is primary.** Use PowerShell for all CLI commands. Path separators in examples use `/` for cross-tool compatibility, but Windows backslash `\` is equally valid in PowerShell.
7879## Version contract (r160+, assume ~r165)
8081Write and expect modern API. When copying code from old tutorials, rewrite these red flags on sight:
8283| Legacy (pre-r152/r155) | Modern (r160+) |
84|---|---|
85| `import X from 'three/examples/jsm/...'` | `import X from 'three/addons/...'` |
86| `renderer.outputEncoding = THREE.sRGBEncoding` | `renderer.outputColorSpace = THREE.SRGBColorSpace` (already the default) |
87| `texture.encoding = THREE.sRGBEncoding` | `texture.colorSpace = THREE.SRGBColorSpace` |
88| `renderer.physicallyCorrectLights = true` | Default behavior; `useLegacyLights` is removed (r165) |
89| `renderer.gammaOutput / gammaFactor` | Gone — color management handles it |
90| `THREE.Geometry` | `THREE.BufferGeometry` only |
91| GammaCorrectionShader at end of composer | `OutputPass` (r154+) |
9293Other r160+ facts to rely on:
9495- Color/albedo/emissive textures need `texture.colorSpace = THREE.SRGBColorSpace`; normal/roughness/metalness/AO/data textures stay linear (`NoColorSpace`). `GLTFLoader` sets this correctly for you.
96- `BatchedMesh` (r159+) batches *different* geometries sharing one material into one draw call; `InstancedMesh` repeats *one* geometry.
97- `renderer.setAnimationLoop(fn)` is the canonical loop driver (required for WebXR; equivalent to rAF otherwise).
98- `WebGPURenderer` + TSL node materials exist and are maturing; target `WebGLRenderer` for shipping games, note WebGPU as forward-looking only.
99100## Procedure
101102### 1. Scaffold the project
103104```powershell
105npm create vite@latest my-game -- --template vanilla-ts
106cd my-game
107npm i three
108npm i -D @types/three
109npm i @dimforge/rapier3d-compat # only if physics chosen (see table below)
110```
111112For the full scaffold (index.html, CSS, vite.config, entry, resize handling) load `recipes.md`.
113114### 2. Configure renderer defaults
115116```ts
117const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' });
118renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); // ALWAYS clamp DPR
119renderer.setSize(window.innerWidth, window.innerHeight);
120renderer.toneMapping = THREE.ACESFilmicToneMapping;
121renderer.shadowMap.enabled = true;
122renderer.shadowMap.type = THREE.PCFSoftShadowMap;
123```
124125### 3. Build the game loop (fixed-timestep)
126127Canonical pattern — fixed-timestep simulation with clamped frame delta and render-side interpolation:
128129```ts
130const FIXED_DT = 1 / 60;
131const MAX_FRAME = 0.25; // tab-away / breakpoint guard
132let accumulator = 0;
133let last = performance.now();
134135renderer.setAnimationLoop(() => {
136 const now = performance.now();
137 const frame = Math.min((now - last) / 1000, MAX_FRAME);
138 last = now;
139 accumulator += frame;
140141 input.poll(); // one snapshot per frame
142 while (accumulator >= FIXED_DT) {
143 simulate(FIXED_DT); // gameplay + physics.step(FIXED_DT)
144 accumulator -= FIXED_DT;
145 }
146 const alpha = accumulator / FIXED_DT;
147 syncVisuals(alpha); // interpolate body → mesh transforms
148 updatePresentation(frame); // mixers, camera damp, particles, HUD
149 renderer.render(scene, camera); // or composer.render()
150});
151```
152153**Loop rules:**
154- Never step physics with a variable dt.
155- Clamp the frame delta or a background tab will explode the simulation on return.
156- Call `clock.getDelta()` at most once per frame (better: own the timing as above).
157- Pause = stop accumulating, keep rendering.
158159Full loop class with timescale and `visibilitychange` handling → load `recipes.md`. Where the loop lives in the codebase → load `architecture.md`.
160161### 4. Set up the asset pipeline (glTF-first)
162163- **One format: `.glb`** (binary glTF). It carries meshes, PBR materials, skins, morphs, and animations. FBX/OBJ only as intermediate DCC formats — convert before shipping. Authoring rules → `game-assets-pipeline`.
164- **Compression:** Draco (smallest geometry, one-time decode cost) or Meshopt (near-Draco size, much faster decode, also compresses animation) — prefer Meshopt via `gltf-transform optimize`. Textures: KTX2/Basis (stays compressed on GPU — the only fix for texture *memory*, not just download size).
165- **Decoders:** `DRACOLoader` and `KTX2Loader` need their decoder/transcoder folders copied into `public/` (from `node_modules/three/examples/jsm/libs/`). `MeshoptDecoder` is a pure JS/WASM module import. Wiring recipe → `recipes.md`.
166- **Preload via a typed manifest** before gameplay; show progress from `LoadingManager`. Loading mid-gameplay causes hitches (decode + GPU upload). Warm shaders with `renderer.compileAsync(scene, camera)` after load.
167- **Never `.clone()` a skinned mesh** — use `SkeletonUtils.clone()` (`three/addons/utils/SkeletonUtils.js`).
168- Cache by URL; share geometries/materials across instances; refcount before disposing shared assets (see Memory rules below).
169170### 5. Choose and wire collision / physics
171172| Situation | Choice |
173|---|---|
174| Puzzle/menu-driven, no dynamics | **No physics.** Transforms + `MathUtils` + distance checks |
175| Character vs static level, picking, hitscan | **three-mesh-bvh** — BVH-accelerated raycast/shapecast against level geometry; write your own kinematics |
176| Rigid-body dynamics, stacks, joints, robust character controller | **Rapier** (`@dimforge/rapier3d-compat`) — fast WASM, ships a `KinematicCharacterController` (slopes, steps, snap-to-ground). Default for real physics |
177| Tiny bundle, simple dynamics, WASM disallowed | **cannon-es** — pure JS, easy API, slower, weaker trimesh support |
178| Legacy ammo.js codebase | Maintain only; don't start new projects on it |
179180**Integration rules:**
181- The physics world steps **inside the fixed update** with `FIXED_DT`.
182- Copy body transforms to meshes after stepping (physics owns dynamic transforms — never write mesh positions back except for kinematic bodies).
183- Build colliders from simplified shapes (capsule/box/hull), not render meshes.
184- Never scale a mesh to "resize" its collider.
185186Sync architecture → load `architecture.md`. Full Rapier setup + character controller → load `recipes.md`.
187188### 6. Wire input
189190- Use **Pointer Events** (`pointerdown/move/up` + `setPointerCapture`) — one code path for mouse, touch, and pen. Never mix in `mousedown`/`touchstart` handlers alongside.
191- Abstract device → **action map** (`moveX/moveY/jump/fire`), then gameplay reads a per-frame snapshot. Enables rebinding, gamepad, touch, and replays without touching game code. Pattern → load `architecture.md`.
192- Gamepad API is poll-based: read `navigator.getGamepads()` once per frame inside `input.poll()`; apply a dead zone (~0.15).
193- Keyboard: track `event.code` (layout-independent) in a `Set`; ignore repeats; clear the set on `blur`.
194- Pointer lock (`canvas.requestPointerLock()`) for FPS-style mouselook; must be called from a user gesture; listen for `pointerlockchange` to pause on Esc.
195196### 7. Mobile pass
197198- `touch-action: none` on the canvas CSS or the browser will scroll/zoom instead of sending you pointermoves.
199- Clamp DPR to 1.5–2; expose a render-scale setting (`renderer.setPixelRatio` is your cheapest quality knob).
200- Virtual joystick = two pointer regions (left stick, right look) tracked by pointerId — hand-rolled recipe in `recipes.md`; multi-touch means you must track pointers by id, never "the" pointer.
201- Budgets drop hard: ≤100–150 draw calls, ≤300k triangles, one shadow-casting light or baked/blob shadows, skip postprocessing on low-end.
202- Handle `visibilitychange` (pause + mute), `orientationchange`/resize, and WebGL `webglcontextlost`/`restored` (prevent default, rebuild).
203- Audio and fullscreen require a user gesture: unlock `AudioContext` on first tap.
204- Test with real CPU throttling (DevTools 6×) — desktop GPUs hide sins.
205206### 8. Postprocessing (EffectComposer)
207208- Use `EffectComposer` with `OutputPass` (r154+) as the final pass — do not use `GammaCorrectionShader`.
209- Ensure the composer survives resize: call `composer.setSize(w, h)` and `composer.setPixelRatio(dpr)` alongside the renderer resize.
210- On mobile/low-end, skip postprocessing entirely or reduce to a single pass.
211212Bloom composer recipe → load `recipes.md`.
213214### 9. Memory & dispose discipline
215216Removing an object from the scene frees **nothing** on the GPU. The rules:
2172181. GPU resources live in `BufferGeometry`, `Material`, `Texture`, `WebGLRenderTarget`, and skeleton bone textures. Each needs `.dispose()` explicitly.
2192. Disposing a material does **not** dispose its textures — walk the material's texture slots.
2203. Shared assets: refcount. Disposing a geometry/material still used elsewhere causes silent re-upload or broken rendering.
2214. Level teardown checklist: stop the loop's spawners → remove event listeners → free physics bodies → traverse and deep-dispose the level subtree → clear pools → verify. Deep-dispose utility → load `recipes.md`.
2225. Verify with `renderer.info.memory` (geometries/textures counts) — it must return to baseline after a load→unload cycle. If it climbs, you leak.
2236. Full app teardown (SPA route change): also `renderer.dispose()`, `renderer.forceContextLoss()`, drop the canvas.
224225Per-frame allocations are the other memory sin: no `new Vector3()` / `.clone()` in the loop — hoist scratch temps to module scope and `.copy()` into them.
226227### 10. Production build with Vite
228229- Ensure decoder files (DRACO, KTX2) are in `public/` and referenced by absolute path.
230- Set `base` in `vite.config.ts` if the game is served from a subpath.
231- Use code splitting for large assets or optional modes (e.g., WebXR).
232- Enable compression plugins (`vite-plugin-compression` for gzip/brotli).
233- Run `npm run build` and verify the output serves correctly from the target path.
234235Full production build config → load `recipes.md`.
236237### 11. WebXR (light mode, if requested)
238239- `renderer.xr.enabled = true`, add `VRButton`/`XRButton` from `three/addons/webxr/`.
240- Drive everything through `renderer.setAnimationLoop` (rAF does not fire in XR sessions).
241- Per-eye rendering roughly doubles GPU cost: drop postprocessing first, keep DPR at 1, use `renderer.xr.setFramebufferScaleFactor` to trade sharpness for frame rate.
242- Controllers via `renderer.xr.getController(i)` with `select` events.
243- Treat XR as a bonus mode, not the primary target, unless the user says otherwise.
244245## Mental model: anatomy of a frame
246247```
248poll input (snapshot devices once)
249 → fixed-step simulation ×N (gameplay logic, physics.step(FIXED_DT))
250 → sync visuals (copy/interpolate body transforms → meshes)
251 → variable-rate update (AnimationMixer, camera damping, particles, UI)
252 → render (renderer or EffectComposer)
253```
254255Scene graph rules that prevent 80% of beginner bugs:
256257- An `Object3D`'s `position/quaternion/scale` are **local** to its parent. World transform lives in `matrixWorld`, updated during render (or via `updateWorldMatrix(true, false)` when you need it mid-frame).
258- `parent.add(child)` re-parents and *changes world position* unless you use `parent.attach(child)` (keeps world transform).
259- Nothing renders without: a camera in a sane position, a light (for lit materials), and geometry with a material. Debug "black screen" in that order.
260- One renderer, one canvas, one loop. Multiple scenes/cameras are fine (HUD pass, minimap) — multiple renderers are not.
261262## Performance budgets & triage
263264| Symptom | First suspects |
265|---|---|
266| High CPU, low GPU | Draw calls (`renderer.info.render.calls`), per-frame allocation/GC, matrix updates on thousands of static objects (`matrixAutoUpdate = false`), unbatched raycasting |
267| High GPU, frame drops at high DPR | Fill rate/overdraw (transparent layers, post passes), shadow map size, DPR unclamped |
268| Hitches/stutters | Mid-gameplay loading, shader compilation (warm with `compileAsync`), GC pauses, texture decode/upload |
269| Memory climbs per level | Missing dispose (rule 5 above) |
270271**Targets:** desktop web ≤ ~1000 draw calls / ≤ 2–3M tris; mobile web ≤ ~150 calls / ≤ 300k tris; 16.6ms frame with ≥ 4ms headroom.
272273**Weapons:** `InstancedMesh`/`BatchedMesh`, `BufferGeometryUtils.mergeGeometries` for static clumps, LOD, frustum-friendly scene structure, shared materials, KTX2 textures, render-scale slider. Methodology → `game-performance-profiling`; ship gate → `web-game-release-review`.
274275## React (r3f) policy
276277Default answer is **vanilla Three.js**. Only if the user explicitly wants React, switch to `@react-three/fiber` + `drei` and keep the paradigm pure — never drive a vanilla imperative scene from React state per frame, and never `setState` inside `useFrame`. Concept mapping when translating:
278279| Vanilla | r3f |
280|---|---|
281| `scene.add(mesh)` | JSX: `<mesh>` declares graph; unmount auto-disposes |
282| `renderer.setAnimationLoop` | `useFrame((state, delta) => ...)` with `useRef` mutation |
283| Manual loaders + cache | `useGLTF` / `useLoader` (suspense, cached) |
284| Manual resize | `<Canvas>` handles it |
285| This skill's loop/physics/memory rules | Still apply — fixed step via accumulator inside `useFrame`, `@react-three/rapier` for physics |
286287## Pitfalls
2882891. `new Vector3/Quaternion/Matrix4` (or `.clone()`) inside the loop — GC churn; hoist scratch objects.
2902. Per-entity `new Material()`/`new Geometry()` for identical entities — share and instance.
2913. Stepping physics with variable frame dt — non-deterministic, explodes on hitches.
2924. Unclamped `setPixelRatio(devicePixelRatio)` — a DPR-3 phone renders 9× the pixels.
2935. Removing meshes without disposing (leak), or disposing shared assets in use (breakage) — refcount.
2946. Loading assets on demand mid-gameplay — preload via manifest; hitches are a design failure.
2957. Raycasting the whole scene recursively every frame — target lists, `layers`, or three-mesh-bvh.
2968. `clock.getDelta()` called from multiple places — each call resets it; own timing centrally.
2979. No frame-delta clamp — returning from a background tab teleports/explodes everything.
29810. `transparent: true` everywhere — overdraw + sort popping; use `alphaTest` for cutouts.
29911. Shadow maps on every light / 4096 maps by default — one sun-shadow + cheats first.
30012. Updating DOM HUD (`innerText`, styles) every frame unconditionally — write on change only.
30113. Copy-pasting pre-r152 tutorial code without applying the Version-contract table above.
30214. `scene.traverse()` per frame to find objects — cache references at spawn time.
30315. `matrixAutoUpdate` left on for thousands of static objects.
30416. Sequential `await load(); await load();` — `Promise.all` the manifest.
30517. Mixing r3f and vanilla idioms in one codebase.
30618. Using `.clone()` on a skinned mesh instead of `SkeletonUtils.clone()` — broken skinning.
30719. Forgetting `texture.colorSpace = THREE.SRGBColorSpace` for color textures loaded outside `GLTFLoader`.
30820. Not handling `webglcontextlost` — the game silently dies on context switch.
309310## Verification
311312Run through this checklist before calling a task done:
313314- [ ] `renderer.info.memory` returns to baseline after a level load→unload cycle
315- [ ] `renderer.info.render.calls` within budget on the heaviest scene
316- [ ] 60 fps with DevTools 6× CPU throttle (or explicit 30 fps mobile target held)
317- [ ] No per-frame allocations in the hot path (DevTools allocation sampling while idling in-game)
318- [ ] Touch: joystick + camera work simultaneously (multi-touch by pointerId), page doesn't scroll
319- [ ] Tab-away 30s → return: no physics explosion, audio muted while hidden
320- [ ] Context-lost handler present; resize/orientation handled; DPR clamped
321- [ ] Production `vite build` served from a subpath works (decoder files, base path)
322- [ ] Ship gate run via `web-game-release-review`
323324### Quick verification commands
325326```powershell
327# Confirm Three.js version is r160+
328npm ls three
329330# Run the dev server
331npm run dev
332333# Production build
334npm run build
335336# Preview the production build
337npm run preview
338```
339340**Expected `npm ls three` output:** `three@0.160.0` or higher.
341342**Expected `renderer.info.memory` check (in console during gameplay):**
343```ts
344console.log(renderer.info.memory); // { geometries: N, textures: M }
345```
346After a full load→unload cycle, N and M must return to their pre-load baseline. If they climb, there is a leak.
347348## Progress checklist (working a task)
3493501. [ ] Scaffold or locate project; confirm three version ≥ r160 and Vite config (load `recipes.md`)
3512. [ ] Renderer defaults + resize + DPR clamp in place
3523. [ ] Fixed-timestep loop owns all timing; delta clamped
3534. [ ] Physics choice made from the table and wired in the fixed step
3545. [ ] Asset manifest preloads everything; decoders wired; skinned clones via SkeletonUtils
3556. [ ] Input action map covers keyboard + pointer + touch (+ gamepad if asked)
3567. [ ] Dispose path written *with* the spawn path, not after
3578. [ ] Mobile pass: budgets, touch-action, visibilitychange, audio unlock
3589. [ ] Run the Verification checklist above before calling it done
359360## Related skills
361362- `browser-game-architecture` — web-game shell, menus, saves, meta-loop
363- `game-3d-rendering` — lighting theory, PBR, post look-dev, quality tiers
364- `game-assets-pipeline` — DCC export, glTF authoring, texture budgets
365- `game-camera-system` — camera feel: follow rigs, shake, framing
366- `game-input-handling` — input abstraction patterns (engine-agnostic)
367- `game-performance-profiling` — profiling methodology and tooling
368- `web-game-release-review` — shipping: perf audit, compatibility, release checklist
Run npx get-skill add kayforkind/threejs-game-development in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
Owns the Three.js r160+ layer of a browser 3D game: scene graph, glTF with DRACO/KTX2, animation, Rapier or cannon-es, EffectComposer, dispose, and Vite. Use when starting or fixing a vanilla Three.js/WebGL web game (r3f only if asked). Not for the HTML5 game shell (browser-game-architecture), cross-engine FPS diagnosis (webgl-performance-tuning), Godot/Unity, or 2D Canvas/Pixi. It is listed under Coding & Dev Tools on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Independent scanners report: SkillSpector: PASS, Skill Scanner: PASS. Capability flags: docs only. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
Kayforkind (@kayforkind) published this skill. Their other Agent Skills are listed on their SkillMD profile.