
Threejs Game
- 599 installs
- 305 repo stars
- Updated May 25, 2026
- opusgamelabs/game-creator
threejs-game is a Claude Code skill that bootstraps a maintainable browser Three.js game with EventBus messaging, centralized GameState, shared constants, and a Game.js orchestrator for developers who need a decoupled mo
About
threejs-game is a game-architecture skill from opusgamelabs/game-creator that ships full implementation code for four non-negotiable core modules: EventBus singleton, GameState, shared Constants, and a Game.js orchestrator. The EventBus enforces that all inter-module communication flows through pub/sub listeners with on, once, and off APIs, so gameplay, UI, and systems never import each other directly. GameState centralizes mutable play data while Constants hold tuning values in one place. Developers reach for threejs-game when starting a new Three.js title and want proven separation of concerns instead of ad-hoc globals or circular imports. The patterns mirror production browser-game structure and pair with the parent game-creator workflow for assets and scenes.
- Non-negotiable core modules: EventBus singleton, centralized GameState, Constants, and Game.js orchestrator
- Domain:action event naming with try/catch-isolated listeners—no direct cross-module imports for communication
- once/off/clear lifecycle on a single exported eventBus instance
- GameState singleton pattern for all mutable play data
- Reference implementations linked from parent game-creator SKILL.md
Threejs Game by the numbers
- 599 all-time installs (skills.sh)
- +22 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #39 of 247 Game Development skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 4, 2026 (Skillselion catalog sync)
npx skills add https://github.com/opusgamelabs/game-creator --skill threejs-gameAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 599 |
|---|---|
| repo stars | ★ 305 |
| Security audit | 2 / 3 scanners passed |
| Last updated | May 25, 2026 |
| Repository | opusgamelabs/game-creator ↗ |
How do you structure a maintainable Three.js browser game?
Bootstrap a maintainable browser Three.js game with EventBus messaging, centralized GameState, shared constants, and a Game.js orchestrator.
Who is it for?
JavaScript developers starting a new browser Three.js game who want enforced module boundaries before gameplay code spreads.
Skip if: Teams building Unity, Unreal, or native desktop games where Three.js and browser canvas are not the runtime.
When should I use this skill?
The developer asks to scaffold, refactor, or standardize architecture for a new or messy Three.js browser game.
What you get
EventBus singleton, GameState module, Constants file, and Game.js orchestrator wired for decoupled browser gameplay.
- EventBus module
- GameState module
- Constants file
By the numbers
- Defines 4 non-negotiable core modules: EventBus, GameState, Constants, and Game.js
Files
Three.js Game Development
You are an expert Three.js game developer. Follow these opinionated patterns when building 3D browser games.
Reference: Seereference/llms.txt(quick guide) andreference/llms-full.txt(full API + TSL) for official Three.js LLM documentation. Prefer patterns from those files when they conflict with this skill.
Performance Notes
- Take your time with each step. Quality is more important than speed.
- Do not skip validation steps — they catch issues early.
- Read the full context of each file before making changes.
- Profile before optimizing. The bottleneck is rarely where you think.
Reference Files
For detailed reference, see companion files in this directory:
core-patterns.md— Full EventBus, GameState, Constants, and Game.js orchestrator codetsl-guide.md— Three.js Shading Language reference (NodeMaterial classes, when to use TSL)input-patterns.md— Gyroscope input, virtual joystick, unified analog InputSystem, input priority system
For performance optimization patterns with measured before/after evidence, see the threejs-perf skill (skills/threejs-perf/SKILL.md).
Tech Stack
- Renderer: Three.js (
three@0.183.0+, ESM imports) - Build Tool: Vite
- Language: JavaScript (not TypeScript) for game templates — TypeScript optional
- Package Manager: npm
Project Setup
When scaffolding a new Three.js game:
mkdir <game-name> && cd <game-name>
npm init -y
npm install three@^0.183.0
npm install -D viteCreate vite.config.js:
import { defineConfig } from 'vite';
export default defineConfig({
root: '.',
publicDir: 'public',
server: { port: 3000, open: true },
build: { outDir: 'dist' },
});Add to package.json scripts:
{
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
}Modern Import Patterns
Vite / npm (default — used in our templates)
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';Import Maps / CDN (standalone HTML games, no build step)
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.183.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.183.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
</script>Use import maps when shipping a single HTML file with no build tooling. Pin the version in the import map URL.
Required Architecture
Every Three.js game MUST use this directory structure:
src/
├── core/
│ ├── Game.js # Main orchestrator - init systems, render loop
│ ├── EventBus.js # Singleton pub/sub for all module communication
│ ├── GameState.js # Centralized state singleton
│ └── Constants.js # ALL config values, balance numbers, asset paths
├── systems/ # Low-level engine systems
│ ├── InputSystem.js # Keyboard/mouse/gamepad input
│ ├── PhysicsSystem.js # Collision detection
│ └── ... # Audio, particles, etc.
├── gameplay/ # Game mechanics
│ └── ... # Player, enemies, weapons, etc.
├── level/ # Level/world building
│ ├── LevelBuilder.js # Constructs the game world
│ └── AssetLoader.js # Loads models, textures, audio
├── ui/ # User interface
│ └── ... # Game over, overlays
└── main.js # Entry point - creates Game instanceCore Principles
1. Core loop first — Implement one camera, one scene, one gameplay loop. Add player input and a terminal condition (win/lose) before adding visual polish. Keep initial scope small: 1 mechanic, 1 fail condition, 1 scoring system. 2. Gameplay clarity > visual complexity — Treat 3D as a style choice, not a complexity mandate. A readable game with simple materials beats a visually complex but confusing one. 3. Restart-safe — Gameplay must be fully restart-safe. GameState.reset() must restore a clean slate. Dispose geometries/materials/textures on cleanup. No stale references or leaked listeners across restarts.
Core Patterns (Non-Negotiable)
Every Three.js game requires these four core modules. Full implementation code is in core-patterns.md.
1. EventBus Singleton
ALL inter-module communication goes through an EventBus (core/EventBus.js). Modules never import each other directly for communication. Provides on, once, off, emit, and clear methods. Events use domain:action naming (e.g., player:hit, game:over). See core-patterns.md for the full implementation.
2. Centralized GameState
One singleton (core/GameState.js) holds ALL game state. Systems read from it, events update it. Must include a reset() method that restores a clean slate for restarts. See core-patterns.md for the full implementation.
3. Constants File
Every magic number, balance value, asset path, and configuration goes in core/Constants.js. Never hardcode values in game logic. Organize by domain: PLAYER_CONFIG, ENEMY_CONFIG, WORLD, CAMERA, COLORS, ASSET_PATHS. See core-patterns.md for the full implementation.
4. Game.js Orchestrator
The Game class (core/Game.js) initializes everything and runs the render loop. Uses renderer.setAnimationLoop() -- the official Three.js pattern (handles WebGPU async correctly and pauses when the tab is hidden). Sets up renderer, scene, camera, systems, UI, and event listeners in init(). See core-patterns.md for the full implementation.
Renderer Selection
WebGLRenderer (default — use for all game templates)
Maximum browser compatibility. Well-established, most examples and tutorials use this. Our templates default to WebGLRenderer.
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer({ antialias: true });WebGPURenderer (when you need TSL or compute shaders)
Required for custom node-based materials (TSL), compute shaders, and advanced rendering. Note: import path changes to 'three/webgpu' and init is async.
import * as THREE from 'three/webgpu';
const renderer = new THREE.WebGPURenderer({ antialias: true });
await renderer.init();When to pick WebGPU: You need TSL custom shaders, compute shaders, or node-based materials. Otherwise, stick with WebGL. See tsl-guide.md for TSL details.
Play.fun Safe Zone
When games run inside the Play.fun dashboard on mobile Safari, the SDK sets CSS custom properties on the game iframe's document.documentElement:
--ogp-safe-top-inset— space below the Play.fun header bubbles (~68px on mobile)--ogp-safe-bottom-inset— space above Safari bottom controls (~148px on mobile)
Both default to 0px when not running inside the dashboard (desktop, standalone).
Constants
// In Constants.js — reads SDK CSS vars with static fallbacks
function _readSafeInsets() {
const s = getComputedStyle(document.documentElement);
return {
top: parseInt(s.getPropertyValue('--ogp-safe-top-inset')) || 0,
bottom: parseInt(s.getPropertyValue('--ogp-safe-bottom-inset')) || 0,
};
}
const _insets = _readSafeInsets();
export const SAFE_ZONE = {
TOP_PX: Math.max(75, _insets.top),
BOTTOM_PX: _insets.bottom,
TOP_PERCENT: 8,
};CSS Rule
All .overlay elements (game-over, pause, menus) must use the CSS variables for padding:
.overlay {
padding-top: max(20px, 8vh, var(--ogp-safe-top-inset, 0px));
padding-bottom: var(--ogp-safe-bottom-inset, 0px);
}Bottom-positioned UI (joysticks, action buttons) must also respect the bottom inset:
#joystick-zone {
bottom: max(20px, 3vh, var(--ogp-safe-bottom-inset, 0px));
}
.bottom-hud {
margin-bottom: var(--ogp-safe-bottom-inset, 0px);
}What to Check
- No text, buttons, or interactive elements in the top or bottom inset areas
- Game-over overlays center content in the usable area (between both insets), not the full viewport
- Score displays, titles, and restart buttons are all visible and not hidden behind browser chrome
- Bottom-positioned controls (joysticks, action buttons) are not clipped by Safari bottom bar
Note: The 3D canvas itself renders behind the chrome, which is fine — the game should bleed to fill the full viewport. Only HTML overlay UI needs the safe zone offset. In-world 3D elements (HUD textures, floating text) should avoid the top 8% and bottom inset of screen space.
Performance Rules
- Use `renderer.setAnimationLoop()` instead of manual
requestAnimationFrame. It pauses when the tab is hidden and handles WebGPU async correctly. - Cap delta time:
Math.min(clock.getDelta(), 0.1)to prevent death spirals - Cap pixel ratio:
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2))— avoids GPU overload on high-DPI screens - Object pooling: Reuse
Vector3,Box3, temp objects in hot loops to minimize GC. Avoid per-frame allocations — preallocate and reuse. - Disable shadows on first pass — Only enable shadow maps when specifically needed and tested on mobile. Dynamic shadows are the single most expensive rendering feature.
- Keep draw calls low — Fewer unique materials and geometries = fewer draw calls. Merge static geometry where possible. Use instanced meshes for repeated objects. See
skills/threejs-perf/for InstancedMesh patterns (~9,000× fewer draw calls, ~57× faster render CPU). - Prefer simple materials — Use
MeshBasicMaterialorMeshStandardMaterial. AvoidMeshPhysicalMaterial, custom shaders, or complex material setups unless specifically needed. - No postprocessing by default — Skip bloom, SSAO, motion blur, and other postprocessing passes on first implementation. These tank mobile performance. Add only after gameplay is solid and perf budget allows.
- Keep geometry/material count small — A game with 10 unique materials renders faster than one with 100. Reuse materials across objects with the same appearance.
- Use `powerPreference: 'high-performance'` on the renderer
- Dispose properly: Call
.dispose()on geometries, materials, textures when removing objects - Frustum culling: Let Three.js handle it (enabled by default) but set bounding spheres on custom geometry
Asset Loading
- Place static assets in
/public/for Vite - Use GLB format for 3D models (smaller, single file)
- Use
THREE.TextureLoader,GLTFLoaderfromthree/addons - Show loading progress via callbacks to UI
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const loader = new GLTFLoader();
function loadModel(path) {
return new Promise((resolve, reject) => {
loader.load(
path,
(gltf) => resolve(gltf.scene),
undefined,
(error) => reject(error),
);
});
}Input Handling (Mobile-First)
All games MUST work on desktop AND mobile unless explicitly specified otherwise. Allocate 60% effort to mobile / 40% desktop when making tradeoffs. Choose the best mobile input for each game concept:
| Game Type | Primary Mobile Input | Fallback |
|---|---|---|
| Marble/tilt/balance | Gyroscope (DeviceOrientation) | Virtual joystick |
| Runner/endless | Tap zones (left/right half) | Swipe gestures |
| Puzzle/turn-based | Tap targets (44px min) | Drag & drop |
| Shooter/aim | Virtual joystick + tap-to-fire | Dual joysticks |
| Platformer | Virtual D-pad + jump button | Tilt for movement |
Unified Analog InputSystem
Use a dedicated InputSystem that merges keyboard, gyroscope, and touch into a single analog interface. Game logic reads moveX/moveZ (-1..1) and never knows the source. Keyboard input is always active as an override; on mobile, the system initializes gyroscope (with iOS 13+ permission request) or falls back to a virtual joystick. See input-patterns.md for the full implementation, including GyroscopeInput, VirtualJoystick, and input priority patterns.
When Adding Features
1. Create a new module in the appropriate src/ subdirectory 2. Define new events in EventBus.js Events object using domain:action naming 3. Add configuration to Constants.js 4. Add state to GameState.js if needed 5. Wire it up in Game.js orchestrator 6. Communicate with other systems ONLY through EventBus
Pre-Ship Validation Checklist
Before considering a game complete, verify:
- [ ] Core loop works — Player can start, play, lose/win, and see the result
- [ ] Restart works cleanly —
GameState.reset()restores a clean slate, all Three.js resources disposed - [ ] Touch + keyboard input — Game works on mobile (gyro/joystick/tap) and desktop (keyboard/mouse)
- [ ] Responsive canvas — Renderer resizes on window resize, camera aspect updated
- [ ] All values in Constants — Zero hardcoded magic numbers in game logic
- [ ] EventBus only — No direct cross-module imports for communication
- [ ] Resource cleanup — Geometries, materials, textures disposed when removed from scene
- [ ] No postprocessing — Unless explicitly needed and tested on mobile
- [ ] Shadows disabled — Unless explicitly needed and budget allows
- [ ] Delta-capped movement —
Math.min(clock.getDelta(), 0.1)on every frame - [ ] Mute toggle — Audio can be muted/unmuted;
isMutedstate is respected - [ ] Safe zone respected — All HTML overlay UI uses
var(--ogp-safe-top-inset)/var(--ogp-safe-bottom-inset)for Play.fun safe area; bottom controls offset above the bottom inset - [ ] Build passes —
npm run buildsucceeds with no errors - [ ] No console errors — Game runs without uncaught exceptions or WebGL failures
Core Patterns -- EventBus, GameState, Constants, Game.js Orchestrator
Full implementation code for the four non-negotiable core modules in every Three.js game. These are referenced from the main SKILL.md.
1. EventBus Singleton
ALL inter-module communication goes through an EventBus. Modules never import each other directly for communication.
class EventBus {
constructor() {
this.listeners = new Map();
}
on(event, callback) {
if (!this.listeners.has(event)) this.listeners.set(event, new Set());
this.listeners.get(event).add(callback);
return () => this.off(event, callback);
}
once(event, callback) {
const wrapper = (...args) => {
this.off(event, wrapper);
callback(...args);
};
this.on(event, wrapper);
}
off(event, callback) {
const cbs = this.listeners.get(event);
if (cbs) {
cbs.delete(callback);
if (cbs.size === 0) this.listeners.delete(event);
}
}
emit(event, data) {
const cbs = this.listeners.get(event);
if (cbs) cbs.forEach(cb => {
try { cb(data); } catch (e) { console.error(`EventBus error [${event}]:`, e); }
});
}
clear(event) {
event ? this.listeners.delete(event) : this.listeners.clear();
}
}
export const eventBus = new EventBus();
// Define ALL events as constants — use domain:action naming
export const Events = {
// Group by domain: player:*, enemy:*, game:*, ui:*, etc.
};2. Centralized GameState
One singleton holds ALL game state. Systems read from it, events update it.
import { PLAYER_CONFIG } from './Constants.js';
class GameState {
constructor() {
this.player = {
health: PLAYER_CONFIG.HEALTH,
score: 0,
};
this.game = {
started: false,
paused: false,
isPlaying: false,
};
}
reset() {
this.player.health = PLAYER_CONFIG.HEALTH;
this.player.score = 0;
this.game.started = false;
this.game.paused = false;
this.game.isPlaying = false;
}
}
export const gameState = new GameState();3. Constants File
Every magic number, balance value, asset path, and configuration goes in Constants.js. Never hardcode values in game logic.
export const PLAYER_CONFIG = {
HEALTH: 100,
SPEED: 5,
JUMP_FORCE: 8,
};
export const ENEMY_CONFIG = {
SPEED: 3,
HEALTH: 50,
SPAWN_RATE: 2000,
};
export const WORLD = {
WIDTH: 100,
HEIGHT: 50,
GRAVITY: 9.8,
FOG_DENSITY: 0.04,
};
export const CAMERA = {
FOV: 75,
NEAR: 0.01,
FAR: 100,
};
export const COLORS = {
AMBIENT: 0x404040,
DIRECTIONAL: 0xffffff,
FOG: 0x000000,
};
export const ASSET_PATHS = {
// model paths, texture paths, etc.
};4. Game.js Orchestrator
The Game class initializes everything and runs the render loop. Uses renderer.setAnimationLoop() -- the official Three.js pattern (handles WebGPU async correctly and pauses when the tab is hidden):
import * as THREE from 'three';
import { CAMERA, COLORS, WORLD } from './Constants.js';
class Game {
constructor() {
this.clock = new THREE.Clock();
this.init();
}
init() {
this.setupRenderer();
this.setupScene();
this.setupCamera();
this.setupSystems();
this.setupUI();
this.setupEventListeners();
this.renderer.setAnimationLoop(() => this.animate());
}
setupRenderer() {
this.renderer = new THREE.WebGLRenderer({
antialias: false,
powerPreference: 'high-performance',
});
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
this.renderer.setSize(window.innerWidth, window.innerHeight);
document.getElementById('game-container').appendChild(this.renderer.domElement);
window.addEventListener('resize', () => this.onWindowResize());
}
setupScene() {
this.scene = new THREE.Scene();
this.scene.fog = new THREE.FogExp2(COLORS.FOG, WORLD.FOG_DENSITY);
this.scene.add(new THREE.AmbientLight(COLORS.AMBIENT, 0.5));
const dirLight = new THREE.DirectionalLight(COLORS.DIRECTIONAL, 1);
dirLight.position.set(5, 10, 5);
this.scene.add(dirLight);
}
setupCamera() {
this.camera = new THREE.PerspectiveCamera(
CAMERA.FOV,
window.innerWidth / window.innerHeight,
CAMERA.NEAR,
CAMERA.FAR,
);
}
setupSystems() {
// Initialize game systems
}
setupUI() {
// Initialize UI overlays
}
setupEventListeners() {
// Subscribe to EventBus events
}
onWindowResize() {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
}
animate() {
const delta = Math.min(this.clock.getDelta(), 0.1); // Cap delta to prevent spiral
// Update all systems with delta
this.renderer.render(this.scene, this.camera);
}
}
export default Game;Input Patterns -- Gyroscope & Virtual Joystick
Detailed implementation patterns for mobile input in Three.js games. These are used as components within the unified InputSystem described in the main SKILL.md.
Gyroscope Input Pattern
For tilt-controlled games (marble, balance, racing):
class GyroscopeInput {
constructor() {
this.available = false;
this.moveX = 0;
this.moveZ = 0;
this.calibBeta = null;
this.calibGamma = null;
}
async requestPermission() {
// iOS 13+: DeviceOrientationEvent.requestPermission()
// Must be called from a user gesture handler
}
recalibrate() {
// Capture current orientation as neutral position
}
update() {
// Apply deadzone, normalize to -1..1, smooth with EMA
}
}Key Implementation Notes
- Permission: iOS 13+ requires
DeviceOrientationEvent.requestPermission()called from a user gesture (tap/click) - Calibration: Store the initial beta/gamma values when the user starts playing; subtract these as the "zero" point
- Deadzone: Apply a 2-3 degree deadzone around neutral to prevent drift
- Smoothing: Use exponential moving average (EMA) to smooth jittery readings
- Normalization: Map tilt angles to -1..1 range with configurable sensitivity
Virtual Joystick Pattern
DOM-based circle-in-circle touch joystick for non-gyro devices:
class VirtualJoystick {
constructor() {
this.active = false;
this.moveX = 0; // -1..1
this.moveZ = 0; // -1..1
}
show() {
// Create outer circle + inner knob DOM elements
// Track touch by identifier to handle multi-touch correctly
// Clamp knob movement to maxDistance from center
// Normalize displacement to -1..1
}
hide() { /* Remove DOM, reset values */ }
}Key Implementation Notes
- DOM-based: Use HTML elements overlaid on the canvas, not canvas-rendered (simpler hit detection)
- Touch tracking: Use
touch.identifierto track the correct finger, not array index - Clamping: Clamp the knob to a circular boundary (not square) using distance calculation
- Positioning: Place in lower-left corner, sized at ~120px diameter for thumb reach
- Opacity: Semi-transparent (0.4-0.6) to not obscure gameplay
Input Priority
1. On mobile: try gyroscope first (request permission from PLAY button tap) 2. If gyro denied/unavailable: show virtual joystick 3. Keyboard always active as fallback/override on any platform 4. Game logic consumes only input.moveX and input.moveZ -- never knows the source
Unified Analog InputSystem
The InputSystem merges keyboard, gyroscope, and touch into a single analog interface. Game logic reads moveX/moveZ (-1..1) and never knows the source:
class InputSystem {
constructor() {
this.keys = {};
this.moveX = 0; // -1..1
this.moveZ = 0; // -1..1
this.isMobile = /Android|iPhone|iPad|iPod/i.test(navigator.userAgent) ||
(navigator.maxTouchPoints > 1);
document.addEventListener('keydown', (e) => { this.keys[e.code] = true; });
document.addEventListener('keyup', (e) => { this.keys[e.code] = false; });
}
/** Call from a user gesture (e.g. PLAY button) to init gyro/joystick. */
async initMobile() {
// Request gyroscope permission (required on iOS 13+)
// If denied/unavailable, show virtual joystick fallback
}
/** Call once per frame. Merges all sources into moveX/moveZ. */
update() {
let mx = 0, mz = 0;
// Keyboard (always active, acts as override)
if (this.keys['ArrowLeft'] || this.keys['KeyA']) mx -= 1;
if (this.keys['ArrowRight'] || this.keys['KeyD']) mx += 1;
if (this.keys['ArrowUp'] || this.keys['KeyW']) mz -= 1;
if (this.keys['ArrowDown'] || this.keys['KeyS']) mz += 1;
const kbActive = mx !== 0 || mz !== 0;
if (!kbActive) {
// Read from gyro or joystick (whichever is active)
}
this.moveX = Math.max(-1, Math.min(1, mx));
this.moveZ = Math.max(-1, Math.min(1, mz));
}
}The GyroscopeInput and VirtualJoystick classes above are used as components within this unified system. The InputSystem's initMobile() method instantiates the appropriate component based on device capabilities.
# Three.js
> Three.js is a cross-browser JavaScript library for creating 3D graphics using WebGL and WebGPU.
## Instructions for Large Language Models
When generating Three.js code, follow these guidelines:
### 1. Use Import Maps (Not Old CDN Patterns)
WRONG - outdated pattern:
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
```
CORRECT - modern pattern (always use latest version):
```html
<script type="importmap">
{
"imports": {
"three": "https://cdn.jsdelivr.net/npm/three@0.183.0/build/three.module.js",
"three/addons/": "https://cdn.jsdelivr.net/npm/three@0.183.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
</script>
```
### 2. Choosing Between WebGLRenderer and WebGPURenderer
Three.js maintains both renderers:
**Use WebGLRenderer** (default, mature):
- Maximum browser compatibility
- Well-established, many years of development
- Most examples and tutorials use this
```js
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer();
```
**Use WebGPURenderer** when you need:
- Custom shaders/materials using TSL (Three.js Shading Language)
- Compute shaders
- Advanced node-based materials
```js
import * as THREE from 'three/webgpu';
const renderer = new THREE.WebGPURenderer();
await renderer.init();
```
### 3. TSL (Three.js Shading Language)
When using WebGPURenderer, use TSL instead of raw GLSL for custom materials:
```js
import { texture, uv, color } from 'three/tsl';
const material = new THREE.MeshStandardNodeMaterial();
material.colorNode = texture( myTexture ).mul( color( 0xff0000 ) );
```
TSL benefits:
- Works with both WebGL and WebGPU backends
- No string manipulation or onBeforeCompile hacks
- Type-safe, composable shader nodes
- Automatic optimization
### 4. NodeMaterial Classes (for WebGPU/TSL)
When using TSL, use node-based materials:
- MeshBasicNodeMaterial
- MeshStandardNodeMaterial
- MeshPhysicalNodeMaterial
- LineBasicNodeMaterial
- SpriteNodeMaterial
## Getting Started
- [Installation](https://threejs.org/manual/#en/installation)
- [Creating a Scene](https://threejs.org/manual/#en/creating-a-scene)
- [Fundamentals](https://threejs.org/manual/#en/fundamentals)
- [Responsive Design](https://threejs.org/manual/#en/responsive)
## Renderer Guides
- [WebGPURenderer](https://threejs.org/manual/#en/webgpurenderer)
## Core Concepts
- [TSL Specification](https://threejs.org/docs/#api/en/nodes/TSL): Complete shader language reference
- [Animation System](https://threejs.org/manual/#en/animation-system)
- [Loading 3D Models](https://threejs.org/manual/#en/loading-3d-models)
- [Scene Graph](https://threejs.org/manual/#en/scenegraph)
- [Materials](https://threejs.org/manual/#en/materials)
- [Textures](https://threejs.org/manual/#en/textures)
- [Lights](https://threejs.org/manual/#en/lights)
- [Cameras](https://threejs.org/manual/#en/cameras)
- [Shadows](https://threejs.org/manual/#en/shadows)
## Essential API
### Core
- [Object3D](https://threejs.org/docs/#api/en/core/Object3D)
- [BufferGeometry](https://threejs.org/docs/#api/en/core/BufferGeometry)
- [BufferAttribute](https://threejs.org/docs/#api/en/core/BufferAttribute)
### Scenes
- [Scene](https://threejs.org/docs/#api/en/scenes/Scene)
### Cameras
- [PerspectiveCamera](https://threejs.org/docs/#api/en/cameras/PerspectiveCamera)
- [OrthographicCamera](https://threejs.org/docs/#api/en/cameras/OrthographicCamera)
### Renderers
- [WebGLRenderer](https://threejs.org/docs/#api/en/renderers/WebGLRenderer)
- [WebGPURenderer](https://threejs.org/docs/#api/en/renderers/webgpu/WebGPURenderer)
### Objects
- [Mesh](https://threejs.org/docs/#api/en/objects/Mesh)
- [InstancedMesh](https://threejs.org/docs/#api/en/objects/InstancedMesh)
- [Group](https://threejs.org/docs/#api/en/objects/Group)
### Materials
- [MeshBasicMaterial](https://threejs.org/docs/#api/en/materials/MeshBasicMaterial)
- [MeshStandardMaterial](https://threejs.org/docs/#api/en/materials/MeshStandardMaterial)
- [MeshPhysicalMaterial](https://threejs.org/docs/#api/en/materials/MeshPhysicalMaterial)
### Geometries
- [BoxGeometry](https://threejs.org/docs/#api/en/geometries/BoxGeometry)
- [SphereGeometry](https://threejs.org/docs/#api/en/geometries/SphereGeometry)
- [PlaneGeometry](https://threejs.org/docs/#api/en/geometries/PlaneGeometry)
### Lights
- [AmbientLight](https://threejs.org/docs/#api/en/lights/AmbientLight)
- [DirectionalLight](https://threejs.org/docs/#api/en/lights/DirectionalLight)
- [PointLight](https://threejs.org/docs/#api/en/lights/PointLight)
- [SpotLight](https://threejs.org/docs/#api/en/lights/SpotLight)
### Loaders
- [TextureLoader](https://threejs.org/docs/#api/en/loaders/TextureLoader)
- [GLTFLoader](https://threejs.org/docs/#examples/en/loaders/GLTFLoader)
### Controls
- [OrbitControls](https://threejs.org/docs/#examples/en/controls/OrbitControls)
- [TransformControls](https://threejs.org/docs/#examples/en/controls/TransformControls)
### Math
- [Vector2](https://threejs.org/docs/#api/en/math/Vector2)
- [Vector3](https://threejs.org/docs/#api/en/math/Vector3)
- [Matrix4](https://threejs.org/docs/#api/en/math/Matrix4)
- [Quaternion](https://threejs.org/docs/#api/en/math/Quaternion)
- [Color](https://threejs.org/docs/#api/en/math/Color)
TSL (Three.js Shading Language)
TSL is Three.js's cross-backend shading language -- write shader logic in JavaScript instead of raw GLSL/WGSL. Works with both WebGL and WebGPU backends.
Basic Example
import { texture, uv, color } from 'three/tsl';
const material = new THREE.MeshStandardNodeMaterial();
material.colorNode = texture(myTexture).mul(color(0xff0000));NodeMaterial Classes (for TSL)
Use node-based material variants when writing TSL shaders:
MeshBasicNodeMaterialMeshStandardNodeMaterialMeshPhysicalNodeMaterialLineBasicNodeMaterialSpriteNodeMaterial
When to Use TSL
- Custom animated materials (color cycling, vertex displacement)
- Procedural textures (noise, patterns)
- Compute shaders for particle systems or physics
- Cross-backend compatibility (same code on WebGL and WebGPU)
For the full TSL specification, functions, and node types, see reference/llms-full.txt.
Renderer Requirement
TSL requires the WebGPU renderer. Import path changes to 'three/webgpu' and init is async:
import * as THREE from 'three/webgpu';
const renderer = new THREE.WebGPURenderer({ antialias: true });
await renderer.init();If you don't need TSL or compute shaders, stick with WebGLRenderer for maximum compatibility.
Related skills
How it compares
Pick threejs-game over generic Three.js tutorials when you need enforced architectural modules, not isolated rendering demos.
FAQ
What modules does threejs-game require?
threejs-game mandates four core modules in every Three.js browser game: an EventBus singleton for messaging, centralized GameState, shared Constants, and a Game.js orchestrator that wires systems together without direct cross-imports.
How does threejs-game handle inter-module communication?
threejs-game routes all communication through an EventBus singleton with on, once, and off listener APIs. Modules subscribe and publish events instead of importing each other directly, which keeps gameplay, UI, and systems decoupled.
Is Threejs Game safe to install?
skills.sh reports 2 of 3 security scanners passed. Review the Security Audits panel on this page before installing in production.