Build 3D browser games with three.js. Project setup (or the Bash game-kit-3d when the space offers it), renderer, scene, camera and resize, the game loop with clock and fixed physics steps, loading glTF models and textures, animation mixers, physics with Rapier or simple custom collisions, third-person and first-person cameras, lighting and shadows on a budget, performance (draw calls, instanci...
Download skill (.zip) Files on GitHubthree.js game development
In Bash: if the space offers game-kit-3d (three.js + Rapier), use it and follow its skill. This skill is for
everything else and for general three.js know-how. Never load WebGL pages in the sandbox browser: use look_at_preview
or check_gpu_render.
Setup (no kit)
<script type="importmap">{ "imports": { "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/" } }</script>
Pin the version. Vendor the files into the project before publishing to itch.io (no CDN surprises offline).
import * as THREE from "three";
const renderer = new THREE.WebGLRenderer({ antialias: devicePixelRatio < 2, powerPreference: "high-performance" });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(60, 1, 0.1, 500);
function resize() { const w = innerWidth, h = innerHeight; renderer.setSize(w, h, false); renderer.domElement.style.cssText = `width:${w}px;height:${h}px`; camera.aspect = w / h; camera.updateProjectionMatrix(); }
addEventListener("resize", resize); resize();
const clock = new THREE.Clock(); let acc = 0; const STEP = 1 / 60;
renderer.setAnimationLoop(() => {
acc += Math.min(clock.getDelta(), 0.25);
while (acc >= STEP) { update(STEP); acc -= STEP; } // game logic + physics at a fixed step
mixers.forEach((m) => m.update(STEP)); // or real dt for animations
renderer.render(scene, camera);
});
Assets
- Models: glTF/GLB (
GLTFLoader), compressed with Draco or meshopt for big files. Textures: power-of-two sizes, ≤ 1024–2048 px, KTX2 if many. Load everything behind a loading screen (LoadingManager). - Animations: one
AnimationMixerper character; crossfade withaction.crossFadeTo(next, 0.2). Map game states to clips (see sprite-animation’s state-machine idea). - Reuse geometry and materials. Clone with
SkeletonUtils.clonefor skinned models.
Physics and collisions
- Real physics: Rapier (
@dimforge/rapier3d-compat, WASM, no threads, so it works in the Bash iframe). Step it inupdate, copy body transforms to meshes. Keep colliders simple (boxes, capsules, convex hulls), never full render meshes. - Simple games: custom collisions (capsule vs AABB, raycast down for ground with
Raycasteragainst a few ground meshes only).
Cameras
- Third-person: target = player position + offset rotated by yaw;
camera.position.lerp(target, 1 - Math.exp(-8 * dt)); raycast from player to camera to avoid walls;camera.lookAt(player + headOffset). - First-person:
PointerLockControlson desktop (pointer lock may be blocked in iframes; fall back to drag-to-look). On touch: left-half joystick to move, right-half drag to look (mobile-game-controls). - Movement relative to the camera: project camera forward onto the ground plane.
Lighting on a budget
One HemisphereLight + one DirectionalLight with shadows covers most games. Shadow map 1024–2048, a tight shadow camera
around the player (move it with the player), castShadow only on things that matter. Bake lighting into textures for
static scenes. See game-lighting for more.
Performance
- Watch
renderer.info.render.calls(draw calls): aim < 200 on phones. UseInstancedMeshfor repeated things (trees, coins, bullets). - Merge static geometry (
BufferGeometryUtils.mergeGeometries). Use fog plus a short far plane to cut distant objects. - No allocation in the loop: reuse
Vector3s (const tmp = new THREE.Vector3()at module level). dispose()geometries, materials and textures when removing levels, or memory grows on every restart.- Mobile: pixel ratio ≤ 2 (try 1.5), fewer lights, no post-processing by default, test on a real phone via the viewer preview.
Bash notes
- Register
bash.preview.onCapture(bash-js-sdk skill) so preview screenshots aren’t blank. - Handle
webglcontextlost: show a “tap to reload” message instead of a frozen frame.