
Threejs Builder
- 4 installs
- 33 repo stars
- Updated December 31, 2025
- chongdashu/threejs-forest-census
Create Three.js web apps with scene setup, GLTF model loading, animations, and game patterns using modern ES modules.
About
Builds Three.js scenes with the scene-graph model plus references for GLTF loading, game patterns, and post-processing. Used when a developer creates 3D web content or scenes.
- GLTF loading, caching, and cloning guidance
- Game patterns and reference-frame calibration
Threejs Builder by the numbers
- 4 all-time installs (skills.sh)
- Ranked #1,817 of 2,245 Frontend Development skills by installs in the Skillselion catalog
- Data as of Jul 28, 2026 (Skillselion catalog sync)
npx skills add https://github.com/chongdashu/threejs-forest-census --skill threejs-builderAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 4 |
|---|---|
| repo stars | ★ 33 |
| Last updated | December 31, 2025 |
| Repository | chongdashu/threejs-forest-census ↗ |
What it does
Create Three.js web apps with scene setup, GLTF model loading, animations, and game patterns using modern ES modules.
Files
Three.js Builder
A focused skill for creating simple, performant Three.js web applications using modern ES module patterns.
Reference Files
Important: Read the appropriate reference file when working on specific topics.
| Topic | File | Use When |
|---|---|---|
| GLTF Models | gltf-loading-guide.md | Loading, caching, cloning 3D models, SkeletonUtils |
| Reference Frames | reference-frame-contract.md | Calibration, anchoring, axis correctness, debugging |
| Game Development | game-patterns.md | State machines, animation switching, parallax, object pooling |
| Advanced Topics | advanced-topics.md | Post-processing, shaders, physics, instancing |
| Calibration Helpers | scripts/README.md | GLTF calibration helper installation and usage |
---
Philosophy: The Scene Graph Mental Model
Three.js is built on the scene graph—a hierarchical tree of objects where parent transformations affect children. Understanding this mental model is key to effective 3D web development.
Before creating a Three.js app, ask:
- What is the core visual element? (geometry, shape, model)
- What interaction does the user need? (none, orbit controls, custom input)
- What performance constraints exist? (mobile, desktop, WebGL capabilities)
- What animation brings it to life? (rotation, movement, transitions)
Core principles:
1. Scene Graph First: Everything added to scene renders. Use Group for hierarchical transforms. 2. Primitives as Building Blocks: Built-in geometries (Box, Sphere, Torus) cover 80% of simple use cases. 3. Animation as Transformation: Change position/rotation/scale over time using requestAnimationFrame or renderer.setAnimationLoop. 4. Performance Through Simplicity: Fewer objects, fewer draw calls, reusable geometries/materials.
---
Three.js Coordinate System (CRITICAL)
Understanding Three.js's right-handed coordinate system is essential to avoid inverted movement, wrong-facing models, and broken collision detection.
The Axes
+Y (up)
|
|
|_______ +X (right)
/
/
+Z (toward camera/viewer)Memory aid: Point your thumb (+X), index finger (+Y), middle finger (+Z) - that's right-handed coordinates.
| Axis | Direction | Common Usage |
|---|---|---|
| +X | Right | Strafe right, spawn right |
| -X | Left | Strafe left, spawn left |
| +Y | Up | Jump, height |
| -Y | Down | Fall, gravity |
| +Z | Toward camera | Approach viewer, "forward" in many setups |
| -Z | Away from camera | Retreat, GLTF models face -Z by default |
GLTF Model Default Orientation
CRITICAL: GLTF models exported from Blender/Maya face -Z (into the screen) by default.
// GLTF model faces -Z. To face +Z (toward camera):
model.rotation.y = Math.PI; // 180° rotation
// To face +X (right):
model.rotation.y = -Math.PI / 2; // -90°
// To face -X (left):
model.rotation.y = Math.PI / 2; // +90°Camera-Relative Movement (CRITICAL for Games)
PROBLEM: When camera is at an angle (e.g., isometric view), raw WASD input moves wrong!
// ❌ WRONG - Input is world-axis relative, not camera-relative
if (keyW) player.position.z -= speed; // Moves toward -Z, not "forward" from player's view
if (keyD) player.position.x += speed; // Moves +X, not "right" from camera's view
// ✓ CORRECT - Calculate camera-relative directions
function updateMovement(deltaTime) {
// Get camera's forward direction, projected onto ground (XZ plane)
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
// Calculate right vector (cross product of forward and world up)
const right = new THREE.Vector3();
right.crossVectors(forward, new THREE.Vector3(0, 1, 0)).normalize();
// Apply input relative to camera orientation
const velocity = new THREE.Vector3();
if (inputState.up) velocity.add(forward);
if (inputState.down) velocity.sub(forward);
if (inputState.right) velocity.add(right);
if (inputState.left) velocity.sub(right);
if (velocity.length() > 0) {
velocity.normalize().multiplyScalar(speed * deltaTime);
player.position.add(velocity);
// Face movement direction
player.rotation.y = Math.atan2(velocity.x, velocity.z);
}
}Why this matters: With camera at (8, 11, -6) looking at (0, 1, 3):
- "Forward" visually is NOT
-Z, it's roughly+Z - "Right" visually is NOT
+X, it's roughly-X + Z - Raw axis input feels completely inverted to players
---
Quick Start: Essential Setup
Minimal HTML Template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three.js App</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { overflow: hidden; background: #000; }
canvas { display: block; }
</style>
</head>
<body>
<script type="module">
import * as THREE from 'https://unpkg.com/three@0.160.0/build/three.module.js';
// Scene setup
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.body.appendChild(renderer.domElement);
// Your 3D content here
// ...
camera.position.z = 5;
// Animation loop
renderer.setAnimationLoop((time) => {
renderer.render(scene, camera);
});
// Handle resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>---
Geometries
Built-in primitives cover most simple app needs. Use BufferGeometry only for custom shapes.
Common primitives:
BoxGeometry(width, height, depth)- cubes, boxesSphereGeometry(radius, widthSegments, heightSegments)- balls, planetsCylinderGeometry(radiusTop, radiusBottom, height)- tubes, cylindersTorusGeometry(radius, tube)- donuts, ringsPlaneGeometry(width, height)- floors, walls, backgroundsConeGeometry(radius, height)- spikes, conesIcosahedronGeometry(radius, detail)- low-poly spheres (detail=0)
Usage:
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x44aa88 });
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);---
Materials
Choose material based on lighting needs and visual style.
Material selection guide:
MeshBasicMaterial- No lighting, flat colors. Use for: UI, wireframes, unlit effectsMeshStandardMaterial- PBR lighting. Default for realistic surfacesMeshPhysicalMaterial- Advanced PBR with clearcoat, transmission. Glass, waterMeshNormalMaterial- Debug, rainbow colors based on normalsMeshPhongMaterial- Legacy, shininess control. Faster than Standard
Common material properties:
{
color: 0x44aa88, // Hex color
roughness: 0.5, // 0=glossy, 1=matte (Standard/Physical)
metalness: 0.0, // 0=non-metal, 1=metal (Standard/Physical)
emissive: 0x000000, // Self-illumination color
wireframe: false, // Show edges only
transparent: false, // Enable transparency
opacity: 1.0, // 0=invisible, 1=opaque (needs transparent:true)
side: THREE.FrontSide // FrontSide, BackSide, DoubleSide
}---
Lighting
No light = black screen (except BasicMaterial/NormalMaterial).
Light types:
AmbientLight(intensity)- Base illumination everywhere. Use 0.3-0.5DirectionalLight(color, intensity)- Sun-like, parallel rays. Cast shadowsPointLight(color, intensity, distance)- Light bulb, emits in all directionsSpotLight(color, intensity, angle, penumbra)- Flashlight, cone of light
Typical lighting setup:
const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(ambientLight);
const mainLight = new THREE.DirectionalLight(0xffffff, 1);
mainLight.position.set(5, 10, 7);
scene.add(mainLight);
const fillLight = new THREE.DirectionalLight(0x88ccff, 0.5);
fillLight.position.set(-5, 0, -5);
scene.add(fillLight);Shadows (advanced, use when needed):
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
mainLight.castShadow = true;
mainLight.shadow.mapSize.width = 2048;
mainLight.shadow.mapSize.height = 2048;
mesh.castShadow = true;
mesh.receiveShadow = true;---
Animation
Transform objects over time using the animation loop.
Animation patterns:
1. Continuous rotation:
renderer.setAnimationLoop((time) => {
mesh.rotation.x = time * 0.001;
mesh.rotation.y = time * 0.0005;
renderer.render(scene, camera);
});2. Wave/bobbing motion:
renderer.setAnimationLoop((time) => {
mesh.position.y = Math.sin(time * 0.002) * 0.5;
renderer.render(scene, camera);
});3. Mouse interaction:
const mouse = new THREE.Vector2();
window.addEventListener('mousemove', (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
});
renderer.setAnimationLoop(() => {
mesh.rotation.x = mouse.y * 0.5;
mesh.rotation.y = mouse.x * 0.5;
renderer.render(scene, camera);
});---
Camera Controls
Import OrbitControls from examples for interactive camera movement:
<script type="module">
import * as THREE from 'https://unpkg.com/three@0.160.0/build/three.module.js';
import { OrbitControls } from 'https://unpkg.com/three@0.160.0/examples/jsm/controls/OrbitControls.js';
// ... scene setup ...
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
renderer.setAnimationLoop(() => {
controls.update();
renderer.render(scene, camera);
});
</script>---
Common Scene Patterns
Rotating Cube (Hello World)
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x00ff88 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
renderer.setAnimationLoop((time) => {
cube.rotation.x = time * 0.001;
cube.rotation.y = time * 0.001;
renderer.render(scene, camera);
});Floating Particle Field
const particleCount = 1000;
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(particleCount * 3);
for (let i = 0; i < particleCount * 3; i += 3) {
positions[i] = (Math.random() - 0.5) * 50;
positions[i + 1] = (Math.random() - 0.5) * 50;
positions[i + 2] = (Math.random() - 0.5) * 50;
}
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const material = new THREE.PointsMaterial({ color: 0xffffff, size: 0.1 });
const particles = new THREE.Points(geometry, material);
scene.add(particles);Animated Background with Foreground Object
// Background grid
const gridHelper = new THREE.GridHelper(50, 50, 0x444444, 0x222222);
scene.add(gridHelper);
// Foreground object
const mainGeometry = new THREE.IcosahedronGeometry(1, 0);
const mainMaterial = new THREE.MeshStandardMaterial({
color: 0xff6600,
flatShading: true
});
const mainMesh = new THREE.Mesh(mainGeometry, mainMaterial);
scene.add(mainMesh);---
Colors
Three.js uses hexadecimal color format: 0xRRGGBB
Common hex colors:
- Black:
0x000000, White:0xffffff - Red:
0xff0000, Green:0x00ff00, Blue:0x0000ff - Cyan:
0x00ffff, Magenta:0xff00ff, Yellow:0xffff00 - Orange:
0xff8800, Purple:0x8800ff, Pink:0xff0088
---
Anti-Patterns to Avoid
Basic Setup Mistakes
❌ Not importing OrbitControls from correct path Why bad: Controls won't load, THREE.OrbitControls is undefined in modern Three.js Better: Use import { OrbitControls } from 'three/addons/controls/OrbitControls.js' or unpkg examples/jsm path
❌ Forgetting to add object to scene Why bad: Object won't render, silent failure Better: Always call scene.add(object) after creating meshes/lights
❌ Using old `requestAnimationFrame` pattern instead of `setAnimationLoop` Why bad: More verbose, doesn't handle XR/WebXR automatically Better: renderer.setAnimationLoop((time) => { ... })
Performance Issues
❌ Creating new geometries in animation loop Why bad: Massive memory allocation, frame rate collapse Better: Create geometry once, reuse it. Transform only position/rotation/scale
❌ Using too many segments on primitives Why bad: Unnecessary vertices, GPU overhead Better: Default segments are usually fine. SphereGeometry(1, 32, 16) not SphereGeometry(1, 128, 64)
❌ Not setting pixelRatio cap Why bad: 4K/5K displays run at full resolution, poor performance Better: Math.min(window.devicePixelRatio, 2)
Code Organization
❌ Everything in one giant function Why bad: Hard to modify, hard to debug Better: Separate setup into functions: createScene(), createLights(), createMeshes()
❌ Hardcoding all values Why bad: Difficult to tweak and experiment Better: Define constants at top: const CONFIG = { color: 0x00ff88, speed: 0.001 }
---
Variation Guidance
IMPORTANT: Each Three.js app should feel unique and context-appropriate.
Vary by scenario:
- Portfolio/showcase: Elegant, smooth animations, muted colors
- Game/interactive: Bright colors, snappy controls, particle effects
- Data visualization: Clean lines, grid helpers, clear labels
- Background effect: Subtle, slow movement, dark/gradient backgrounds
- Product viewer: Realistic lighting, PBR materials, smooth orbit
Vary visual elements:
- Geometry choice: Not everything needs to be a cube. Explore spheres, tori, icosahedra
- Material style: Mix flat shaded, glossy, metallic, wireframe
- Color palettes: Use complementary, analogous, or monochromatic schemes
- Animation style: Rotation, oscillation, wave motion, mouse tracking
Avoid converging on:
- Default green cube as first example every time
- Same camera angle (front-facing, z=5)
- Identical lighting setup (always directional light at 1,1,1)
---
Remember
Three.js is a tool for interactive 3D on the web.
Effective Three.js apps:
- Start with the scene graph mental model
- Use primitives as building blocks
- Keep animations simple and performant
- Vary visual style based on purpose
- Import from modern ES module paths
Modern Three.js (r150+) uses ES modules from `three` package or CDN. CommonJS patterns and global THREE variable are legacy.
Claude is capable of creating elegant, performant 3D web experiences. These patterns guide the way—they don't limit the result.
For specific topics, see the Reference Files table at the top of this document.
Advanced Three.js Topics
Progressive disclosure reference for topics beyond simple scenes.
Note: For GLTF models, seegltf-loading-guide.md. For game development patterns, seegame-patterns.md. Both are accessible from the main SKILL.md reference table.
---
Loading 3D Models (GLTF/GLB)
Quick example using import maps:
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const loader = new GLTFLoader();
loader.load(
'path/to/model.glb',
(gltf) => {
gltf.scene.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
scene.add(gltf.scene);
camera.position.z = 5;
},
(progress) => {
console.log((progress.loaded / progress.total * 100).toFixed(0) + '%');
},
(error) => {
console.error('Failed to load model:', error);
}
);
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
</script>Key improvement: Import maps resolve Three.js module paths correctly, avoiding long unpkg URLs.
---
Post-Processing (Bloom, Depth of Field)
For visual effects like bloom, use the EffectComposer:
<script type="module">
import * as THREE from 'https://unpkg.com/three@0.160.0/build/three.module.js';
import { EffectComposer } from 'https://unpkg.com/three@0.160.0/examples/jsm/postprocessing/EffectComposer.js';
import { RenderPass } from 'https://unpkg.com/three@0.160.0/examples/jsm/postprocessing/RenderPass.js';
import { UnrealBloomPass } from 'https://unpkg.com/three@0.160.0/examples/jsm/postprocessing/UnrealBloomPass.js';
// Basic setup...
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.toneMapping = THREE.ReinhardToneMapping;
// Post-processing
const renderScene = new RenderPass(scene, camera);
const bloomPass = new UnrealBloomPass(
new THREE.Vector2(window.innerWidth, window.innerHeight),
1.5, // strength
0.4, // radius
0.85 // threshold
);
const composer = new EffectComposer(renderer);
composer.addPass(renderScene);
composer.addPass(bloomPass);
renderer.setAnimationLoop(() => {
composer.render();
});
</script>---
Custom Shaders (ShaderMaterial)
For custom visual effects, write GLSL shaders:
const vertexShader = `
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const fragmentShader = `
uniform float time;
varying vec2 vUv;
void main() {
vec3 color = 0.5 + 0.5 * cos(time + vUv.xyx + vec3(0, 2, 4));
gl_FragColor = vec4(color, 1.0);
}
`;
const material = new THREE.ShaderMaterial({
vertexShader,
fragmentShader,
uniforms: {
time: { value: 0 }
}
});
renderer.setAnimationLoop((time) => {
material.uniforms.time.value = time * 0.001;
renderer.render(scene, camera);
});---
Text and Sprites
For 2D text or labels in 3D space:
// Canvas-based text sprite
function createTextSprite(message, scale = 1) {
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = 256;
canvas.height = 64;
context.fillStyle = 'rgba(0, 0, 0, 0)';
context.fillRect(0, 0, canvas.width, canvas.height);
context.font = 'Bold 24px Arial';
context.fillStyle = 'white';
context.textAlign = 'center';
context.fillText(message, canvas.width / 2, canvas.height / 2);
const texture = new THREE.CanvasTexture(canvas);
const material = new THREE.SpriteMaterial({ map: texture });
const sprite = new THREE.Sprite(material);
sprite.scale.set(scale * 4, scale, 1);
return sprite;
}
const label = createTextSprite('Hello Three.js!', 1);
label.position.set(0, 2, 0);
scene.add(label);---
Raycasting (Mouse Picking)
For clicking/touching 3D objects:
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();
window.addEventListener('click', (event) => {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(scene.children);
if (intersects.length > 0) {
const object = intersects[0].object;
// Do something with clicked object
object.material.color.setHex(Math.random() * 0xffffff);
}
});---
Environment Maps (Reflections)
For realistic reflections on metallic surfaces:
import { RGBELoader } from 'https://unpkg.com/three@0.160.0/examples/jsm/loaders/RGBELoader.js';
const rgbeLoader = new RGBELoader();
rgbeLoader.load('path/to/environment.hdr', (texture) => {
texture.mapping = THREE.EquirectangularReflectionMapping;
scene.environment = texture;
scene.background = texture;
});
// Material with reflections
const material = new THREE.MeshStandardMaterial({
color: 0x444444,
metalness: 1,
roughness: 0.1
});---
InstancedMesh (Many Similar Objects)
For rendering thousands of identical objects efficiently:
const count = 1000;
const geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
const material = new THREE.MeshStandardMaterial({ color: 0x44aa88 });
const mesh = new THREE.InstancedMesh(geometry, material, count);
const dummy = new THREE.Object3D();
for (let i = 0; i < count; i++) {
dummy.position.set(
(Math.random() - 0.5) * 20,
(Math.random() - 0.5) * 20,
(Math.random() - 0.5) * 20
);
dummy.rotation.set(Math.random() * Math.PI, Math.random() * Math.PI, 0);
dummy.updateMatrix();
mesh.setMatrixAt(i, dummy.matrix);
}
scene.add(mesh);---
Physics Integration (Cannon.js)
For physics-based interactions:
<script type="module">
import * as THREE from 'https://unpkg.com/three@0.160.0/build/three.module.js';
import * as CANNON from 'https://unpkg.com/cannon-es@0.20.0/dist/cannon-es.js';
// Three.js setup
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Cannon.js world
const world = new CANNON.World();
world.gravity.set(0, -9.82, 0);
// Sync mesh with physics body
const geometry = new THREE.SphereGeometry(0.5);
const material = new THREE.MeshStandardMaterial({ color: 0xff6600 });
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
const body = new CANNON.Body({
mass: 1,
shape: new CANNON.Sphere(0.5),
position: new CANNON.Vec3(0, 5, 0)
});
world.addBody(body);
// Ground
const groundBody = new CANNON.Body({
type: CANNON.Body.STATIC,
shape: new CANNON.Plane()
});
groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0);
world.addBody(groundBody);
const timeStep = 1 / 60;
renderer.setAnimationLoop(() => {
world.step(timeStep);
mesh.position.copy(body.position);
mesh.quaternion.copy(body.quaternion);
renderer.render(scene, camera);
});
</script>---
Installation with npm
For production apps, install Three.js via npm:
npm install threeimport * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// Same API as CDN version---
TypeScript Support
Three.js includes TypeScript definitions:
import * as THREE from 'three';
const scene: THREE.Scene = new THREE.Scene();
const geometry: THREE.BoxGeometry = new THREE.BoxGeometry(1, 1, 1);
const material: THREE.MeshStandardMaterial = new THREE.MeshStandardMaterial({
color: 0x44aa88
});
const cube: THREE.Mesh = new THREE.Mesh(geometry, material);
scene.add(cube);---
Key Module Import Paths (r160+)
// Core
import * as THREE from 'three';
// Addons (three/addons/ in npm, examples/jsm/ in CDN)
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { RGBELoader } from 'three/addons/loaders/RGBELoader.js';
import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';---
Performance Tips
1. Reuse geometries and materials: Create once, use many times 2. Use InstancedMesh: For 100+ identical objects 3. Limit shadow map resolution: 1024-2048 is usually sufficient 4. Disable antialiasing: For pixel art or performance-critical apps 5. Use frustum culling: Objects outside view are skipped (automatic) 6. Merge geometries: Combine static objects into one mesh 7. Use LOD (Level of Detail): Switch to simpler geometries at distance
// Geometry merging
const geometries = [];
for (let i = 0; i < 10; i++) {
geometries.push(new THREE.BoxGeometry(1, 1, 1));
}
const mergedGeometry = BufferGeometryUtils.mergeGeometries(geometries);---
Debug Helpers
// Grid helper
const gridHelper = new THREE.GridHelper(10, 10);
scene.add(gridHelper);
// Axes helper (RGB = XYZ)
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);
// Stats.js for performance monitoring
import Stats from 'https://unpkg.com/three@0.160.0/examples/jsm/libs/stats.module.js';
const stats = new Stats();
document.body.appendChild(stats.dom);
renderer.setAnimationLoop(() => {
stats.begin();
// render...
stats.end();
});Three.js Game Patterns
Patterns for building games with Three.js, beyond simple showcase scenes.
---
Animation State Management
For characters that switch between idle, run, jump, death, etc.
Finding and Playing Animations
// After loading GLTF
const mixer = new THREE.AnimationMixer(model);
const animations = gltf.animations;
// Find animation by name (partial match)
function findAnimation(name) {
return animations.find(clip =>
clip.name.toLowerCase().includes(name.toLowerCase())
);
}
// Play an animation
function playAnimation(name, { loop = true, timeScale = 1 } = {}) {
const clip = findAnimation(name);
if (!clip) return null;
const action = mixer.clipAction(clip);
action.reset();
action.setLoop(loop ? THREE.LoopRepeat : THREE.LoopOnce);
action.clampWhenFinished = !loop; // Hold last frame if not looping
action.timeScale = timeScale;
action.play();
return action;
}
// Usage
playAnimation('run'); // Loop running
playAnimation('jump', { loop: false, timeScale: 2 }); // One-shot, fast
playAnimation('death', { loop: false }); // One-shot, hold last frameCrossfading Between Animations
let currentAction = null;
function switchAnimation(name, { fadeTime = 0.1, ...options } = {}) {
const clip = findAnimation(name);
if (!clip) return;
const newAction = mixer.clipAction(clip);
// CRITICAL: Check if this action is already playing
// Calling reset() on an already-playing action causes frame freezing!
if (currentAction === newAction) {
if (!newAction.isRunning()) {
newAction.play();
}
return; // Don't reset or fade - it's already running
}
newAction.reset();
newAction.setLoop(options.loop !== false ? THREE.LoopRepeat : THREE.LoopOnce);
newAction.clampWhenFinished = !options.loop;
newAction.timeScale = options.timeScale || 1;
newAction.enabled = true;
newAction.paused = false;
if (currentAction) {
currentAction.fadeOut(fadeTime);
}
newAction.fadeIn(fadeTime).play();
currentAction = newAction;
}
// Usage in game loop - safe to call every frame
function updateEntity(entity, dt) {
if (entity.isMoving) {
switchAnimation('run'); // Won't reset if already running
} else {
switchAnimation('idle');
}
}---
Animation Selection Pitfalls (CRITICAL)
GLTF models may have multiple animations. Incorrect selection causes:
- Sheep playing death animations instead of idle
- Wolves frozen (no animation match found)
- Characters stuck in T-pose
Safe Animation Selection
// ❌ WRONG - First animation might be death!
const action = mixer.clipAction(animations[0]);
action.play();
// ❌ WRONG - Partial match might grab wrong animation
const clip = animations.find(a => a.name.includes('idle'));
// "Death_Idle" matches "idle"!
// ✓ CORRECT - Explicit filtering with priority order
function selectSafeAnimation(animations, preferredTypes = ['idle', 'eat', 'graze']) {
// First: filter OUT dangerous animations
const safeAnims = animations.filter(a => {
const name = a.name.toLowerCase();
return !name.includes('death') &&
!name.includes('die') &&
!name.includes('dead');
});
// Second: find preferred animation from safe list
for (const type of preferredTypes) {
const match = safeAnims.find(a =>
a.name.toLowerCase().includes(type)
);
if (match) return match;
}
// Third: use first safe animation
if (safeAnims.length > 0) return safeAnims[0];
// Last resort: use first animation with warning
console.warn('No safe animation found, using:', animations[0]?.name);
return animations[0];
}
// Usage for ambient entities (sheep, birds, etc.)
const clip = selectSafeAnimation(gltf.animations, ['idle', 'eat', 'graze', 'walk']);
mixer.clipAction(clip).play();Animation Matching for Game Entities
function setEntityAnimation(entity, desiredName, options = {}) {
const { loop = true, timeScale = 1 } = options;
// Log available animations on first call (debugging)
if (!entity._animsLogged) {
console.log(`[${entity.type}] Available animations:`,
Object.keys(entity.animations).join(', '));
entity._animsLogged = true;
}
// Try exact match first
let action = entity.animations[desiredName.toLowerCase()];
// Try partial match
if (!action) {
const key = Object.keys(entity.animations).find(k =>
k.toLowerCase().includes(desiredName.toLowerCase())
);
if (key) action = entity.animations[key];
}
// Try common alternatives
if (!action) {
const alternatives = {
'run': ['walk', 'gallop', 'trot', 'move'],
'attack': ['bite', 'punch', 'hit', 'strike'],
'death': ['die', 'dead', 'defeat'],
'idle': ['stand', 'breathe', 'wait']
};
const alts = alternatives[desiredName.toLowerCase()] || [];
for (const alt of alts) {
const key = Object.keys(entity.animations).find(k =>
k.toLowerCase().includes(alt)
);
if (key) {
action = entity.animations[key];
break;
}
}
}
// Last resort: first non-death animation
if (!action) {
const safeKey = Object.keys(entity.animations).find(k => {
const lower = k.toLowerCase();
return !lower.includes('death') && !lower.includes('die');
});
if (safeKey) action = entity.animations[safeKey];
}
if (!action) {
console.warn(`[${entity.type}] No animation found for: ${desiredName}`);
return;
}
// Prevent redundant resets (causes freezing)
if (entity.currentAction === action) {
if (!action.isRunning()) action.play();
return;
}
console.log(`[${entity.type}] Playing: ${action.getClip().name}`);
if (entity.currentAction) {
entity.currentAction.fadeOut(0.15);
}
action.reset();
action.setLoop(loop ? THREE.LoopRepeat : THREE.LoopOnce, loop ? Infinity : 1);
action.clampWhenFinished = !loop;
action.timeScale = timeScale;
action.enabled = true;
action.paused = false;
action.fadeIn(0.15);
action.play();
entity.currentAction = action;
}---
Facing Direction for Side-Scrollers
GLTF models typically face -Z (into the screen). For side-scrollers:
function normalizeModel(model, targetHeight, faceDirection = 'right') {
// ... scaling logic ...
// Rotate to face correct direction
// GLTF default: faces -Z
// To face +X (right): rotate +90° around Y
// To face -X (left): rotate -90° around Y
if (faceDirection === 'right') {
model.rotation.y = Math.PI / 2; // Face +X
} else if (faceDirection === 'left') {
model.rotation.y = -Math.PI / 2; // Face -X
}
// 'none' or default: keep original facing
return model;
}
// Usage
normalizeModel(playerModel, 2, 'right'); // Player runs right
normalizeModel(enemyModel, 2, 'left'); // Enemy approaches from right---
Game Loop with State Machine
const GameState = {
LOADING: 'loading',
MENU: 'menu',
PLAYING: 'playing',
PAUSED: 'paused',
GAME_OVER: 'gameover'
};
const state = {
current: GameState.LOADING,
timeScale: 1.0, // For slow-mo effects
score: 0
};
const clock = new THREE.Clock();
const mixers = []; // All animation mixers
function gameLoop() {
const dt = Math.min(clock.getDelta(), 0.1); // Cap delta for tab-away
const scaledDt = dt * state.timeScale;
// Always update animations (even in menu for idle anims)
for (const mixer of mixers) {
mixer.update(scaledDt);
}
switch (state.current) {
case GameState.PLAYING:
updatePlayer(scaledDt);
updateObstacles(scaledDt);
updateBackground(scaledDt);
checkCollisions();
updateScore(dt); // Real time, not scaled
break;
case GameState.PAUSED:
// Render but don't update physics
break;
case GameState.MENU:
// Light background animation
updateBackground(dt * 0.3);
break;
}
updateScreenEffects(dt);
renderer.render(scene, camera);
}
renderer.setAnimationLoop(gameLoop);---
Time Scaling (Slow Motion)
// Trigger slow-mo
function triggerSlowMo(factor, duration) {
state.timeScale = factor;
setTimeout(() => {
state.timeScale = 1.0;
}, duration * 1000);
}
// Usage
triggerSlowMo(0.3, 0.2); // 30% speed for 0.2 seconds
// Gradual return to normal
function triggerSlowMoSmooth(factor, holdTime, rampTime) {
state.timeScale = factor;
setTimeout(() => {
const startTime = performance.now();
const rampMs = rampTime * 1000;
function ramp() {
const elapsed = performance.now() - startTime;
const t = Math.min(elapsed / rampMs, 1);
state.timeScale = factor + (1 - factor) * t;
if (t < 1) requestAnimationFrame(ramp);
}
ramp();
}, holdTime * 1000);
}
// Usage: 0.15x for 0.2s, then ramp to 1x over 0.12s
triggerSlowMoSmooth(0.15, 0.2, 0.12);---
Screen Effects
Camera Shake
const cameraBasePos = { x: 2, y: 5, z: 16 };
let shakeIntensity = 0;
let shakeDuration = 0;
function shakeScreen(intensity, duration) {
shakeIntensity = intensity;
shakeDuration = duration;
}
function updateShake(dt) {
if (shakeDuration > 0) {
shakeDuration -= dt;
const decay = shakeDuration / 0.3; // Assume 0.3s base duration
const offset = shakeIntensity * decay;
camera.position.x = cameraBasePos.x + (Math.random() - 0.5) * offset;
camera.position.y = cameraBasePos.y + (Math.random() - 0.5) * offset;
} else {
camera.position.x = cameraBasePos.x;
camera.position.y = cameraBasePos.y;
}
}
// Usage
shakeScreen(0.5, 0.35); // Intensity 0.5 units, 0.35 secondsScreen Flash
<div id="flash-overlay" style="
position: absolute;
top: 0; left: 0;
width: 100%; height: 100%;
pointer-events: none;
opacity: 0;
transition: opacity 0.08s;
"></div>function flashScreen(color, duration) {
const overlay = document.getElementById('flash-overlay');
overlay.style.backgroundColor = color;
overlay.style.opacity = 0.3;
setTimeout(() => {
overlay.style.opacity = 0;
}, duration * 1000);
}
// Usage
flashScreen('#4DEBFF', 0.15); // Cyan flash for near-miss
flashScreen('#ffffff', 0.08); // White flash for impactZoom Pulse
let zoomTarget = 1.0;
let zoomCurrent = 1.0;
function zoomPulse(scale, duration) {
zoomTarget = scale;
setTimeout(() => {
zoomTarget = 1.0;
}, duration * 500); // Half duration for in, half for out
}
function updateZoom(dt) {
// Smooth interpolation
zoomCurrent += (zoomTarget - zoomCurrent) * dt * 10;
// Apply to camera FOV (for perspective) or frustum (for ortho)
camera.zoom = zoomCurrent;
camera.updateProjectionMatrix();
}
// Usage
zoomPulse(1.02, 0.2); // 2% zoom in, 0.2s total---
Squash & Stretch
For jump anticipation and landing impact:
function setModelScale(model, sx, sy, sz) {
model.scale.set(sx, sy, sz);
}
// Jump anticipation
function jumpAnticipation(model) {
setModelScale(model, 1.15, 0.8, 1.15); // Squash
setTimeout(() => {
setModelScale(model, 1, 1, 1); // Restore
}, 80);
}
// Landing impact
function landingSquash(model) {
setModelScale(model, 1.2, 0.75, 1.2); // Heavy squash
setTimeout(() => {
setModelScale(model, 0.95, 1.1, 0.95); // Overshoot
}, 60);
setTimeout(() => {
setModelScale(model, 1, 1, 1); // Settle
}, 150);
}---
Parallax Background Layers
Different scroll speeds create depth:
const PARALLAX = {
clouds: 0.1, // Very slow
farTrees: 0.3, // Slow
nearTrees: 0.5, // Medium
crowd: 0.7, // Faster
ground: 1.0 // Base speed
};
const layers = {
clouds: [],
farTrees: [],
nearTrees: [],
crowd: []
};
function updateParallax(dt, baseSpeed) {
for (const [layerName, objects] of Object.entries(layers)) {
const speed = baseSpeed * PARALLAX[layerName] * dt;
for (const obj of objects) {
obj.position.x -= speed;
// Wrap when off-screen
if (obj.position.x < -30) {
obj.position.x += 60; // Jump to right side
// Randomize Z for variety on wrap
obj.position.z = -5 - Math.random() * 10;
}
}
}
}---
Object Pooling
For spawning/despawning obstacles:
class ObjectPool {
constructor(createFn, initialSize = 10) {
this.createFn = createFn;
this.pool = [];
this.active = [];
// Pre-populate
for (let i = 0; i < initialSize; i++) {
const obj = createFn();
obj.visible = false;
this.pool.push(obj);
}
}
spawn(x, y, z) {
let obj = this.pool.pop();
if (!obj) {
// Pool exhausted, create new
obj = this.createFn();
}
obj.position.set(x, y, z);
obj.visible = true;
this.active.push(obj);
return obj;
}
despawn(obj) {
obj.visible = false;
const idx = this.active.indexOf(obj);
if (idx !== -1) this.active.splice(idx, 1);
this.pool.push(obj);
}
// Call in game loop
updateAll(callback) {
// Iterate backwards for safe removal
for (let i = this.active.length - 1; i >= 0; i--) {
const shouldDespawn = callback(this.active[i]);
if (shouldDespawn) {
this.despawn(this.active[i]);
}
}
}
}
// Usage
const obstaclePool = new ObjectPool(() => {
return createObstacle(); // Your creation function
}, 15);
// Spawn
obstaclePool.spawn(12, 0, 0);
// Update loop
obstaclePool.updateAll((obstacle) => {
obstacle.position.x -= scrollSpeed * dt;
return obstacle.position.x < -14; // Return true to despawn
});---
Fixed Game Camera (Not OrbitControls)
For side-scrollers and fixed-view games:
// Simple side-view camera
function setupGameCamera() {
const camera = new THREE.PerspectiveCamera(45, 960/540, 0.1, 100);
camera.position.set(2, 5, 16);
camera.lookAt(2, 1, 0);
return camera;
}
// Cinematic variant with slight tilt
function setupCinematicCamera() {
const camera = new THREE.PerspectiveCamera(50, 960/540, 0.1, 100);
camera.position.set(0, 8, 14);
camera.lookAt(2, 1, 0);
camera.rotation.z = 0.03; // Slight Dutch angle
return camera;
}
// Toggle between camera modes
let cinematicMode = false;
const cameraPositions = {
simple: { x: 2, y: 5, z: 16, fov: 45, tilt: 0 },
cinematic: { x: 0, y: 8, z: 14, fov: 50, tilt: 0.03 }
};
function toggleCameraMode() {
cinematicMode = !cinematicMode;
const pos = cinematicMode ? cameraPositions.cinematic : cameraPositions.simple;
camera.position.set(pos.x, pos.y, pos.z);
camera.fov = pos.fov;
camera.rotation.z = pos.tilt;
camera.updateProjectionMatrix();
camera.lookAt(2, 1, 0);
}---
Near-Miss Detection
For rewarding close calls:
function checkNearMiss(player, obstacle, threshold = 0.8) {
// Only check when obstacle passes player
if (obstacle.position.x > player.position.x) return false;
if (obstacle.passed) return false;
// Mark as passed
obstacle.passed = true;
// Check if it was close (player was above obstacle)
const verticalGap = player.position.y - obstacle.height;
if (verticalGap > 0 && verticalGap < threshold) {
triggerNearMissReward();
return true;
}
return false;
}
function triggerNearMissReward() {
state.score += 15;
flashScreen('#4DEBFF', 0.15);
triggerSlowMo(0.5, 0.15);
showFloatingText('CLOSE!', '#4DEBFF');
}---
Floating Text Popup
<style>
.floating-text {
position: absolute;
font-weight: bold;
pointer-events: none;
animation: floatUp 0.6s ease-out forwards;
}
@keyframes floatUp {
0% { opacity: 1; transform: translateY(0) scale(1); }
100% { opacity: 0; transform: translateY(-40px) scale(1.2); }
}
</style>function showFloatingText(text, color, x = '50%', y = '35%') {
const popup = document.createElement('div');
popup.className = 'floating-text';
popup.textContent = text;
popup.style.color = color;
popup.style.left = x;
popup.style.top = y;
popup.style.transform = 'translateX(-50%)';
popup.style.fontSize = '1.4rem';
popup.style.textShadow = `0 0 10px ${color}`;
document.getElementById('ui').appendChild(popup);
setTimeout(() => popup.remove(), 600);
}---
Best Practices Summary
| Pattern | When to Use |
|---|---|
| Animation state management | Characters with multiple animations |
| Facing direction rotation | Side-scrollers with GLTF models |
| Game state machine | Any game with menu/play/pause/gameover |
| Time scaling | Slow-mo for impact moments |
| Screen shake | Death, heavy impacts |
| Screen flash | Near-miss, milestones, damage |
| Squash & stretch | Jump, land, any snappy motion |
| Parallax layers | Scrolling games with depth |
| Object pooling | Spawning many objects (obstacles, particles) |
| Fixed camera | Games (not model viewers) |
| Near-miss detection | Rewarding close calls |
---
Anti-Patterns
❌ Creating objects in the game loop
// BAD - creates garbage every frame
function update() {
const obstacle = new Obstacle(); // Memory leak!
}❌ Mixing real time and game time inconsistently
// BAD - score affected by slow-mo
state.score += dt * state.timeScale;
// GOOD - score uses real time
state.score += dt;❌ Forgetting to clean up animation mixers
// BAD - mixer keeps running, memory leak
scene.remove(enemy);
// GOOD - remove mixer from update list
const idx = mixers.indexOf(enemy.mixer);
if (idx !== -1) mixers.splice(idx, 1);
scene.remove(enemy);GLTF Loading Guide for Three.js
Modern patterns for loading, managing, and displaying 3D models in Three.js applications.
---
Quick Start: The Minimal Pattern
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GLTF Loader</title>
<style>
* { margin: 0; padding: 0; }
body { overflow: hidden; background: #000; }
canvas { display: block; }
</style>
</head>
<body>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
// Scene setup
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 10, 7);
scene.add(directionalLight);
// Load model
const loader = new GLTFLoader();
loader.load(
'path/to/model.gltf',
(gltf) => {
console.log('Model loaded:', gltf);
scene.add(gltf.scene);
camera.position.z = 5;
},
(progress) => {
console.log((progress.loaded / progress.total * 100).toFixed(0) + '%');
},
(error) => {
console.error('Failed to load model:', error);
}
);
// Animation loop
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
// Handle resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>---
Core Concepts
Import Maps (Essential for ES Modules)
Always use import maps to resolve Three.js module paths correctly:
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}
}
</script>This allows clean imports:
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';---
Pattern 1: Basic Loading
Simplest approach - load a single model and display it.
const loader = new GLTFLoader();
loader.load(
'models/character.gltf',
(gltf) => {
// Success callback
const model = gltf.scene;
// Optional: enable shadows
model.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
scene.add(model);
},
(progress) => {
// Progress callback (optional)
const percentComplete = (progress.loaded / progress.total * 100);
console.log(percentComplete + '% loaded');
},
(error) => {
// Error callback
console.error('Failed to load model:', error);
}
);---
Pattern 2: Promise-Based Loading
For cleaner async/await syntax and easier error handling:
const loader = new GLTFLoader();
function loadModel(path) {
return new Promise((resolve, reject) => {
loader.load(
path,
(gltf) => {
gltf.scene.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
resolve(gltf.scene);
},
(progress) => {
const pct = (progress.loaded / progress.total * 100).toFixed(0);
console.log(`Loading: ${pct}%`);
},
(error) => {
console.error('Load error:', error);
reject(error);
}
);
});
}
// Usage
async function init() {
try {
const model = await loadModel('models/character.gltf');
scene.add(model);
} catch (error) {
console.error('Failed to initialize:', error);
}
}
init();---
Pattern 3: Loading with Fallbacks
Production-ready pattern that gracefully falls back to procedural geometry if GLTF fails:
const loader = new GLTFLoader();
function loadModel(path, fallbackGeometry, fallbackMaterial) {
return new Promise((resolve) => {
loader.load(
path,
(gltf) => {
gltf.scene.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
resolve(gltf.scene);
},
undefined,
(error) => {
console.warn(`Failed to load ${path}, using fallback:`, error);
// Create fallback mesh
const mesh = new THREE.Mesh(fallbackGeometry, fallbackMaterial);
mesh.castShadow = true;
resolve(mesh);
}
);
});
}
// Usage
async function init() {
const playerFallback = new THREE.BoxGeometry(0.4, 0.6, 0.3);
const playerMat = new THREE.MeshStandardMaterial({ color: 0xE9F2FF });
const player = await loadModel(
'assets/Character_Male_1.gltf',
playerFallback,
playerMat
);
scene.add(player);
}
init();---
Pattern 4: Batch Loading Multiple Models
Load several models sequentially with status updates:
const loader = new GLTFLoader();
async function loadAssets(assetList) {
const loaded = {};
for (const asset of assetList) {
try {
console.log(`Loading ${asset.name}...`);
const gltf = await new Promise((resolve, reject) => {
loader.load(asset.path, resolve, undefined, reject);
});
// Configure the model
gltf.scene.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
loaded[asset.name] = gltf.scene;
console.log(`✓ Loaded: ${asset.name}`);
} catch (error) {
console.error(`✗ Failed: ${asset.name}`, error);
// Optionally use fallback here
}
}
return loaded;
}
// Usage
const assets = [
{ name: 'player', path: 'models/character.gltf' },
{ name: 'enemy', path: 'models/skeleton.gltf' },
{ name: 'ground', path: 'models/tile.gltf' }
];
loadAssets(assets).then((models) => {
scene.add(models.player);
scene.add(models.enemy);
// ... position and use models
});---
Pattern 5: Caching & Reuse (with Animation Support)
Load once, clone many times for performance. CRITICAL: Use SkeletonUtils.clone() for animated/skinned models!
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import * as SkeletonUtils from 'three/addons/utils/SkeletonUtils.js';
class ModelCache {
constructor() {
this.loader = new GLTFLoader();
this.cache = new Map();
}
async load(path) {
if (this.cache.has(path)) {
return this.cache.get(path);
}
return new Promise((resolve, reject) => {
this.loader.load(
path,
(gltf) => {
gltf.scene.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
// Store both scene and animations
this.cache.set(path, {
scene: gltf.scene,
animations: gltf.animations
});
resolve(this.cache.get(path));
},
undefined,
reject
);
});
}
clone(path) {
const cached = this.cache.get(path);
if (!cached) {
throw new Error(`Model ${path} not in cache. Load it first.`);
}
// CRITICAL: Use SkeletonUtils.clone for animated models!
// Regular .clone() breaks skeleton bone references
const hasAnimations = cached.animations && cached.animations.length > 0;
return hasAnimations
? SkeletonUtils.clone(cached.scene)
: cached.scene.clone();
}
getAnimations(path) {
return this.cache.get(path)?.animations || [];
}
}
// Usage
const cache = new ModelCache();
const mixers = []; // Track animation mixers for update loop
async function init() {
await cache.load('models/enemy.gltf');
// Spawn multiple animated instances
for (let i = 0; i < 5; i++) {
const enemy = cache.clone('models/enemy.gltf');
enemy.position.x = i * 3;
scene.add(enemy);
// Setup independent animation for each clone
const animations = cache.getAnimations('models/enemy.gltf');
if (animations.length > 0) {
const mixer = new THREE.AnimationMixer(enemy);
mixer.clipAction(animations[0]).play();
mixers.push(mixer);
}
}
}
// In animation loop
function animate() {
const delta = clock.getDelta();
mixers.forEach(mixer => mixer.update(delta));
renderer.render(scene, camera);
}Why SkeletonUtils.clone() is required:
- Regular
.clone()doesn't properly duplicate skeleton/bone hierarchies - Cloned skinned meshes reference the original skeleton's bones
- This causes cloned models to stay at origin or move with the original
SkeletonUtils.clone()creates independent bone hierarchies for each clone
---
Pattern 6: Model Normalization
Scale and position GLTF models consistently.
CRITICAL: Do NOT use box.setFromObject(model) for animated GLTF models! It includes invisible armature bones, helpers, and skeleton rigs which extend far beyond the visible mesh. This causes models to float above the ground.
// ❌ WRONG - includes bones/armatures, model will float
function badNormalize(model, targetSize) {
const box = new THREE.Box3().setFromObject(model); // Includes skeleton!
// ... model will be positioned incorrectly
}
// ✓ CORRECT - only visible mesh geometry
function normalizeModel(model, targetSize = 1.5) {
// Reset transforms
model.position.set(0, 0, 0);
model.rotation.set(0, 0, 0);
// Compute bounding box ONLY from visible mesh geometry
const box = new THREE.Box3();
model.traverse((child) => {
if (child.isMesh && child.geometry) {
child.geometry.computeBoundingBox();
const meshBox = child.geometry.boundingBox.clone();
meshBox.applyMatrix4(child.matrixWorld);
box.union(meshBox);
}
});
// Fallback for models without mesh children
if (box.isEmpty()) {
box.setFromObject(model);
}
const size = box.getSize(new THREE.Vector3());
const maxDim = Math.max(size.x, size.y, size.z);
// Apply uniform scale
const scale = targetSize / maxDim;
model.scale.setScalar(scale);
// Update world matrices after scaling
model.updateMatrixWorld(true);
// Recompute bounds after scale (mesh-only)
const scaledBox = new THREE.Box3();
model.traverse((child) => {
if (child.isMesh && child.geometry) {
const meshBox = child.geometry.boundingBox.clone();
meshBox.applyMatrix4(child.matrixWorld);
scaledBox.union(meshBox);
}
});
if (scaledBox.isEmpty()) {
scaledBox.setFromObject(model);
}
// Position so bottom of visible mesh sits at y=0
model.position.y = -scaledBox.min.y;
return model;
}
// Usage
loader.load('models/character.gltf', (gltf) => {
normalizeModel(gltf.scene, 2.0); // 2 units tall, feet on ground
scene.add(gltf.scene);
});Why this matters:
- GLTF characters have skeleton armatures for animation
- Armature bones (hips, spine, etc.) are positioned at body center, not feet
setFromObject()includes these invisible bones in the bounding box- Result:
box.min.yis much lower than actual feet → model floats
---
Common Pitfalls & Solutions
❌ GLTF Won't Load - File Not Found
Problem: 404 errors for GLTF files
Solutions:
- Verify the file path is correct (relative to HTML file)
- Use a local web server (
python3 -m http.server 8000) - Check browser console for exact error
# Start local server in your project directory
python3 -m http.server 8080
# Visit http://localhost:8080❌ Models Look Wrong - Incorrect Scale/Rotation
Problem: Model is huge, tiny, or upside down
Solution: Use the normalization pattern above, or adjust manually:
loader.load('model.gltf', (gltf) => {
const model = gltf.scene;
// Debug: log original bounds
const box = new THREE.Box3().setFromObject(model);
console.log('Bounds:', box);
// Adjust scale and rotation
model.scale.set(0.5, 0.5, 0.5);
model.rotation.x = Math.PI / 2; // Rotate 90°
scene.add(model);
});❌ Animated Model Floats Above Ground
Problem: Character model hovers above the floor after positioning
Cause: Box3.setFromObject() includes invisible skeleton bones/armatures in the bounding box calculation. Armature origins are typically at hip level, not feet.
Solution: Compute bounds only from visible mesh geometry:
// ❌ WRONG
const box = new THREE.Box3().setFromObject(model);
model.position.y = -box.min.y; // Model floats!
// ✓ CORRECT
const box = new THREE.Box3();
model.traverse((child) => {
if (child.isMesh && child.geometry) {
child.geometry.computeBoundingBox();
const meshBox = child.geometry.boundingBox.clone();
meshBox.applyMatrix4(child.matrixWorld);
box.union(meshBox);
}
});
model.position.y = -box.min.y; // Feet on groundSee Pattern 6: Model Normalization for the complete solution.
❌ Cloned Animated Model Stays at Origin
Problem: You clone a GLTF model but the clone stays at position (0,0,0) and won't move, or moves with the original model instead of independently. May also flicker or render incorrectly.
Cause: Regular .clone() doesn't properly duplicate skeleton/bone hierarchies. The cloned skinned mesh still references the original model's bones.
Solution: Use SkeletonUtils.clone() for any animated/skinned model:
import * as SkeletonUtils from 'three/addons/utils/SkeletonUtils.js';
// ❌ WRONG - clone stays at origin, animations broken
const badClone = model.clone();
badClone.position.x = 5; // Won't work!
// ✓ CORRECT - fully independent clone
const goodClone = SkeletonUtils.clone(model);
goodClone.position.x = 5; // Works!
// Each clone needs its own AnimationMixer
const mixer = new THREE.AnimationMixer(goodClone);
mixer.clipAction(animations[0]).play();Detection: If your model has gltf.animations.length > 0, it likely has a skeleton and needs SkeletonUtils.clone().
---
❌ No Shadows on GLTF Models
Problem: Models don't cast or receive shadows
Solution: Enable shadows on all meshes:
loader.load('model.gltf', (gltf) => {
gltf.scene.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
scene.add(gltf.scene);
});❌ Slow Loading - Large Models Block Scene
Problem: Page freezes while loading
Solution: Load in background, show progress:
const loadingBar = document.getElementById('loading');
loader.load(
'huge-model.glb',
(gltf) => {
scene.add(gltf.scene);
loadingBar.style.display = 'none';
},
(progress) => {
const pct = (progress.loaded / progress.total * 100);
loadingBar.style.width = pct + '%';
},
(error) => {
loadingBar.textContent = 'Load failed';
}
);---
Advanced: Draco Compression
Load compressed GLTF files for smaller file sizes:
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
// Point to Draco decoder
dracoLoader.setDecoderPath('https://www.gstatic.com/draco/v1/decoders/');
loader.setDRACOLoader(dracoLoader);
loader.load('model.glb', (gltf) => {
scene.add(gltf.scene);
});
</script>---
Best Practices Summary
| Practice | Benefit |
|---|---|
| Use import maps | Cleaner imports, works with CDN modules |
| Wrap in promises | Better error handling, easier async/await |
| Add fallbacks | Graceful degradation if models fail |
| Cache & clone | Better performance when spawning many instances |
| SkeletonUtils.clone() | Required for animated/skinned models - regular clone breaks bones |
| Enable shadows | Traverse & set castShadow/receiveShadow |
| Normalize scale | Consistent sizing across different models |
| Mesh-only bounds | Use mesh geometry, not setFromObject() for animated models |
| Show progress | Better UX for large models |
| Use local server | Avoid CORS, proper relative paths |
---
Reference: GLTFLoader Callback Signature
loader.load(
url, // string: path to .gltf or .glb file
onLoad, // function(gltf): called on success
onProgress, // function(progress): called during load
onError // function(error): called on failure
);gltf object contents:
{
scene: Group, // The root scene group
scenes: Array<Group>, // All scenes in the file
animations: Array<Clip>, // Animation clips
cameras: Array<Camera>, // Cameras in the file
asset: Object, // Asset metadata
parser: GLTFParser, // Internal parser (advanced use)
userData: Object // Custom data from file
}progress object:
{
loaded: number, // Bytes loaded
total: number // Total bytes to load
}Reference Frame Contract (Three.js) — Calibration & Guardrails
Most production bugs in Three.js scenes are reference-frame bugs, not rendering bugs. If you lock a "contract" up front, you avoid weeks of symptom-chasing (floating models, inverted axes, broken animations, weird colors, hung state transitions).
1) The Contract (write these down for the project)
Axes
- World axes: +X right, +Y up, +Z ??? (your gameplay forward)
- Camera conventions: do you treat camera forward as "player forward"?
- Per-asset forward: does this asset pack face
-Z,+Z, or something else? - Result: a single
MODEL_FORWARD_OFFSET(radians) or a per-asset override.
Anchors ("what is ground?")
Define how each asset class is anchored relative to y=0:
- Characters: bottom at y=0 (
minY = 0) - Props: bottom at y=0 (
minY = 0) - Ground tiles/blocks: walkable top at y=0 (
maxY = 0) is often the right choice
Units / Scale
- What is 1 unit? (meters-ish, tile-sized, etc.)
- Define target heights in world units:
HERO_HEIGHT,CHICK_HEIGHT, etc.
Color / Output
- Set and keep consistent:
renderer.outputColorSpace = THREE.SRGBColorSpace- If you use atlas-textured GLTFs:
- Keep
material.colornear white (tinting by multiplication often corrupts the look).
Loading Environment
- GLTF must be served over HTTP (avoid
file://), or loaders may fail silently / behave differently.
State Transitions
- One state machine, one transition function, one-way latches for terminal events (
hasEnded).
UI Scaling
- Center via layout (flex/grid) and apply
scale()only. - Avoid mixing
translate()+scale()unless you're very deliberate abouttransform-origin.
2) 60-Second Calibration Pass (do this before gameplay)
1) Add helpers:
scene.add(new THREE.AxesHelper(2))scene.add(new THREE.GridHelper(10, 10))- Add a known ground datum at y=0 (plane or your ground tile)
2) Load one GLTF per class: character, chick, ground tile, a prop. 3) Visualize bounds + pivot:
obj.add(new THREE.AxesHelper(0.5))scene.add(new THREE.Box3Helper(new THREE.Box3().setFromObject(obj), 0xff00ff))
4) Print animation clip names:
console.log(gltf.animations.map(a => a.name))
5) Confirm output color space:
renderer.outputColorSpace = THREE.SRGBColorSpace
6) Decide constants:
MODEL_FORWARD_OFFSET(and/or per-asset overrides)- Anchor mode per asset type (
minYvsmaxY)
Forward Direction Check (Mesh Forward)
You want a deterministic answer to: "Which way is forward for this mesh?"
Three.js convention:
- An
Object3D's forward direction is its local `-Z` axis.
In the calibration scene, attach an arrow to the model root so you can see forward at a glance:
// After normalization, and after any yaw offsets you apply.
const modelRoot = instanceRoot;
modelRoot.add(new THREE.AxesHelper(0.6));
// Visualize local forward (-Z) as a magenta arrow.
const localForward = new THREE.Vector3(0, 0, -1);
const arrow = new THREE.ArrowHelper(localForward, new THREE.Vector3(0, 1.2, 0), 1.2, 0xff00ff);
modelRoot.add(arrow);
// Also log world-forward (the object's -Z axis in world coordinates).
const worldForward = new THREE.Vector3();
modelRoot.getWorldDirection(worldForward);
console.log('model world forward (-Z):', worldForward.toArray());Lock the result as a constant:
- Prefer
yawOffsetper asset class (hero vs enemies), or oneMODEL_YAW_OFFSETif the whole pack is consistent. - Keep this separate from gameplay heading (don't "fix" movement vectors to compensate for wrong mesh forward).
3) Anchoring Pattern (stop "offset roulette")
Normalize imported scenes once, into an anchor wrapper. Then position the wrapper in world space.
function normalizeToAnchor(root, { targetHeight, anchor = 'minY' }) {
const box = new THREE.Box3().setFromObject(root);
const size = box.getSize(new THREE.Vector3());
if (size.y > 0) root.scale.setScalar(targetHeight / size.y);
root.updateMatrixWorld(true);
const box2 = new THREE.Box3().setFromObject(root);
const y = anchor === 'maxY' ? -box2.max.y : -box2.min.y;
root.position.y += y;
root.updateMatrixWorld(true);
}Rules:
- Use one anchor rule per asset class.
- Don't compensate by moving the entire world group or by mixing "surfaceY" computations with per-entity offsets unless you have a clearly defined second contract.
4) Camera-Relative Movement Basis (avoid inverted WASD)
const up = new THREE.Vector3(0, 1, 0);
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
forward.y = 0;
forward.normalize();
// Right-handed: right = forward × up
const right = new THREE.Vector3().crossVectors(forward, up).normalize();If left/right is inverted:
- Check the cross product order first.
- If your camera points "backward" relative to gameplay forward, you may need
forward.negate()— fix the convention, not the key mapping.
5) GLTF Loading & Animation Reliability
Animated instancing
If a model has bones/skin, use:
SkeletonUtils.clone(gltf.scene)for instancesnew THREE.AnimationMixer(instanceRoot)per instance
Clip selection
- Select clips by exact name (log them).
- Only use substring/heuristic matching as an explicit fallback strategy.
Atlas tinting
If your pack uses atlas textures:
- Avoid
material.color.multiply(...)tinting (can turn everything into flat tinted planes). - Prefer emissive, lighting, or a carefully chosen single
material.color.setHex(...)if the pack expects it.
6) Timeout "Hang" Guardrail
Symptoms: timer hits ~0.8s/0.0s and the game appears stuck.
Common causes:
- Multiple systems trigger end state (timer, slowmo, submit) without a latch.
timeLeftgoes negative and your UI/logic path assumes> 0.
Fix pattern:
timeLeft = Math.max(0, timeLeft - dt)- One-way
hasEndedlatch: - if
hasEndedreturn early from timer/update - end transition sets
hasEnded = trueand runs exactly once
7) Quick Troubleshooting Map
- Model floats / sinks → anchor contract missing (minY vs maxY mismatch) or offsets in too many places.
- Forward/back inverted → asset pack forward differs; set
MODEL_FORWARD_OFFSETafter calibration. - Left/right inverted → wrong basis (
crossorder) or inconsistent forward convention. - Red/flat planes → color space not set OR atlas materials tinted incorrectly OR load failed and fallback geometry is showing.
- Canvas not centered → transform-origin/translate+scale drift; center via layout and scale only.
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import pathlib
import shutil
import sys
def main() -> int:
parser = argparse.ArgumentParser(
description="Install the threejs-builder GLTF calibration helper module into a project folder.",
)
parser.add_argument(
"--out",
required=True,
help="Destination path (file) to write, e.g. ./gltf-calibration-helpers.mjs",
)
parser.add_argument(
"--force",
action="store_true",
help="Overwrite if destination exists.",
)
args = parser.parse_args()
src = pathlib.Path(__file__).resolve().parent / "gltf-calibration-helpers.mjs"
if not src.exists():
print(f"[ERR] Missing source module: {src}", file=sys.stderr)
return 2
dst = pathlib.Path(args.out).expanduser().resolve()
dst.parent.mkdir(parents=True, exist_ok=True)
if dst.exists() and not args.force:
print(f"[ERR] Destination exists (use --force): {dst}", file=sys.stderr)
return 2
shutil.copyfile(src, dst)
print(f"[OK] Wrote: {dst}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
threejs-builder scripts
GLTF forward/anchor calibration helper
This skill includes a small ES-module you can copy into your project to make the reference frame contract visible (axes, bounds, and mesh-forward arrow).
Install into your project:
python3 .claude/skills/threejs-builder/scripts/install-gltf-calibration-helpers.py \
--out ./gltf-calibration-helpers.mjsUse in your Three.js ES-module code:
import { attachGltfCalibrationHelpers } from './gltf-calibration-helpers.mjs';
// After you normalize/anchor/scale the model, and after any yaw offsets:
attachGltfCalibrationHelpers({ scene, root: modelRoot, label: 'Hero', showGrid: true });Notes:
- In Three.js, an Object3D's "forward" direction is its local
-Zaxis. root.getWorldDirection(v)gives you the world-space direction of local-Z.