How to Build a Game in Three.js
How to make a web game with Three.js, step by step. A tested starter game, free assets, physics, sound, and where to publish it, updated for late 2026.
If you want to know how to make a web game that people can play from a link, with no download and no app store, Three.js is the most direct route. It is a free JavaScript library for 3D graphics in the browser, and it is the stack AI coding tools handle best, which is why so many vibe-coded games use it.
This Three.js tutorial builds a small complete game: you run around a field and collect ten orbs before a timer runs out. The code was written for the current release and tested in a browser before publishing. After that we cover what turns a demo into a game you can share: assets, physics, sound, performance and publishing.
What Three.js is, and when to use it
Three.js describes itself in three words: "JavaScript 3D library." It draws 3D scenes in a web page. It is not a full game engine, so there is no editor, no built-in physics and no level designer. You write code, and you add the extra pieces you need.
That trade suits web games well:
- It is free. Three.js is released under the MIT licence, with no fees or revenue share.
- It runs everywhere a browser does. Players click a link and play.
- AI tools are good at it. The game is plain text files, which is exactly what a coding agent works with.
The version used here is r187, published on October 30, 2026, which is three@0.187.0 on npm. Three.js releases often, roughly every month or two, so check the releases page for anything newer.
If you want a visual editor, or you are aiming at consoles, a full engine such as Godot or Unity is a better fit. Our guide to making an indie game compares them.
Step 1: Set up the project
You need Node.js installed. Then open a terminal, make a folder, and install Three.js and Vite, the tool that serves your game while you work. These are the commands from the official installation guide:
mkdir orb-dash
cd orb-dash
npm install --save three
npm install --save-dev viteCreate two empty files in that folder, index.html and main.js. Then start the dev server:
npx viteVite prints a local address. Open it in your browser. It will be blank until you add the code below, and it reloads by itself every time you save.
Step 2: Add the page
Put this in index.html. It is a blank page with a line of text in the corner for the score, and it loads your game code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Orb Dash</title>
<style>
body { margin: 0; overflow: hidden; }
#hud { position: fixed; top: 16px; left: 16px; font: 600 20px system-ui, sans-serif; color: #fff; text-shadow: 0 1px 3px #000; }
</style>
</head>
<body>
<div id="hud"></div>
<script type="module" src="/main.js"></script>
</body>
</html>Step 3: Write the game
Put this in main.js. It is the whole game, about 120 lines.
// Orb Dash: collect 10 orbs before the timer runs out. Move with WASD.
// Written for three.js r187 (npm three@0.187.0).
import * as THREE from 'three';
// Scene, camera, renderer
const scene = new THREE.Scene();
scene.background = new THREE.Color( 0x87ceeb );
const camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 0.1, 200 );
const renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( Math.min( window.devicePixelRatio, 2 ) );
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.shadowMap.enabled = true;
renderer.setAnimationLoop( animate );
document.body.appendChild( renderer.domElement );
// Lights. The sun follows the player so the shadow never falls outside its range.
scene.add( new THREE.HemisphereLight( 0xffffff, 0x444444, 1.5 ) );
const sun = new THREE.DirectionalLight( 0xffffff, 2 );
const sunOffset = new THREE.Vector3( 5, 10, 5 );
sun.castShadow = true;
scene.add( sun );
scene.add( sun.target );
// Ground
const ground = new THREE.Mesh(
new THREE.PlaneGeometry( 50, 50 ),
new THREE.MeshStandardMaterial( { color: 0x55aa55 } )
);
ground.rotation.x = - Math.PI / 2;
ground.receiveShadow = true;
scene.add( ground );
// Player: a capsule two units tall
const player = new THREE.Mesh(
new THREE.CapsuleGeometry( 0.5, 1, 4, 16 ),
new THREE.MeshStandardMaterial( { color: 0xff6633 } )
);
player.position.y = 1;
player.castShadow = true;
scene.add( player );
// Orbs to collect
const orbs = [];
const orbGeometry = new THREE.SphereGeometry( 0.3, 16, 16 );
const orbMaterial = new THREE.MeshStandardMaterial( { color: 0xffd23f, emissive: 0x553300 } );
for ( let i = 0; i < 10; i ++ ) {
const orb = new THREE.Mesh( orbGeometry, orbMaterial );
orb.position.set( THREE.MathUtils.randFloatSpread( 40 ), 0.6, THREE.MathUtils.randFloatSpread( 40 ) );
orb.castShadow = true;
scene.add( orb );
orbs.push( orb );
}
// Game state
const hud = document.getElementById( 'hud' );
let score = 0;
let timeLeft = 30;
let state = 'playing'; // 'playing', 'won' or 'lost'
// Input. event.code names the physical key, so WASD works on any keyboard layout.
const keys = new Set();
window.addEventListener( 'keydown', ( event ) => {
keys.add( event.code );
if ( event.code === 'KeyR' && state !== 'playing' ) window.location.reload();
} );
window.addEventListener( 'keyup', ( event ) => keys.delete( event.code ) );
// Timer gives the seconds since the last frame, so speed is the same on every screen.
const timer = new THREE.Timer();
timer.connect( document );
const speed = 6; // units per second
const direction = new THREE.Vector3();
const cameraOffset = new THREE.Vector3( 0, 4, 8 );
function animate( timestamp ) {
timer.update( timestamp );
const delta = Math.min( timer.getDelta(), 0.1 );
if ( state === 'playing' ) {
direction.set(
( keys.has( 'KeyD' ) ? 1 : 0 ) - ( keys.has( 'KeyA' ) ? 1 : 0 ),
0,
( keys.has( 'KeyS' ) ? 1 : 0 ) - ( keys.has( 'KeyW' ) ? 1 : 0 )
);
if ( direction.lengthSq() > 0 ) {
direction.normalize();
player.position.addScaledVector( direction, speed * delta );
player.position.x = THREE.MathUtils.clamp( player.position.x, - 24.5, 24.5 );
player.position.z = THREE.MathUtils.clamp( player.position.z, - 24.5, 24.5 );
player.rotation.y = Math.atan2( direction.x, direction.z );
}
for ( let i = orbs.length - 1; i >= 0; i -- ) {
if ( orbs[ i ].position.distanceTo( player.position ) < 1 ) {
scene.remove( orbs[ i ] );
orbs.splice( i, 1 );
score ++;
}
}
timeLeft -= delta;
if ( orbs.length === 0 ) state = 'won';
else if ( timeLeft <= 0 ) state = 'lost';
}
if ( state === 'playing' ) hud.textContent = `Orbs ${ score }/10 · Time ${ Math.ceil( timeLeft ) }`;
else if ( state === 'won' ) hud.textContent = 'You got them all! Press R to play again';
else hud.textContent = 'Out of time. Press R to try again';
camera.position.copy( player.position ).add( cameraOffset );
camera.lookAt( player.position );
sun.position.copy( player.position ).add( sunOffset );
sun.target.position.copy( player.position );
renderer.render( scene, camera );
}
window.addEventListener( 'resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
} );Save, and you should see an orange capsule on a green field under a blue sky. Move with W, A, S and D.
What the code is doing
Every Three.js game has the same skeleton, and you can see each part above.
- Scene, camera, renderer. The scene holds your objects, the camera decides the view, and the renderer draws it. Those three appear in every project.
- The loop.
setAnimationLoop( animate )callsanimateonce per frame. The docs say applications "are advised to always define the animation loop with this method" (WebGLRenderer). - Delta time.
timer.getDelta()returns the seconds since the last frame. Multiplying movement by it keeps the player's speed the same on a fast screen and a slow one. - Rules. A goal (collect ten orbs), a way to lose (the timer), a score, and a restart key. Those four things are what separate a game from a tech demo.
Step 4: Add real models and art
Shapes are fine for a prototype. For models, the standard format is glTF, which its maintainers at Khronos describe as "a royalty-free specification for the efficient transmission and loading of 3D scenes and models." Three.js loads it with GLTFLoader:
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
const loader = new GLTFLoader();
loader.load( '/models/hero.glb', ( gltf ) => scene.add( gltf.scene ) );With Vite, put the file in a folder named public/models.
Free assets come with different rules. Check the licence before you ship, and most of all before you sell anything.
| Source | What you get | Licence, as stated on the site |
|---|---|---|
| Kenney | Models, sprites, sounds | Public domain (CC0). "Attribution is not required." |
| Poly Haven | Textures, skies, models | "Our assets are all licensed as CC0" |
| ambientCG | Materials and textures | CC0 |
| Quaternius | Low-poly models | Its own licence since August 2026. Free for commercial use, but you cannot resell or redistribute the assets themselves |
| Mixamo | Character animations | Royalty free with an Adobe account, including to "create video games" |
| Poly Pizza | Low-poly models | Varies by model. Check each one |
AI model generators are an option too, and their free tiers come with strings. As of November 2026, Meshy's free plan grants a "CC BY 4.0 license (commercial use with attribution)," and Tripo's free plan is listed as "Non-Commercial Use." A game you plan to sell generally needs a paid plan on either.
Step 5: Collisions and physics
The starter game checks distance between two points, which is enough for pickups. Walls, slopes and jumping need more.
The Three.js manual's physics page lists the libraries it supports. Two are actively maintained and free:
- Rapier, under the Apache 2.0 licence. A good default.
- Jolt, under the MIT licence.
An older library, cannon-es, appears in a lot of tutorials. Its last release was in 2022 and the manual describes it as "apparently no longer maintained," so skip it for new projects.
If you only need a character to walk around a level without falling through it, look at the official first-person example. It handles collisions without a physics engine.
Step 6: Sound
Three.js has audio built in: an AudioListener on the camera, plus Audio for music and PositionalAudio for sounds that come from a place in the world.
The one rule that catches everyone: browsers block sound until the player interacts with the page. Chrome's autoplay policy explains that an audio context created before a user gesture starts "in the 'suspended' state." The fix is simple. Show a "Click to play" button and start your audio when it is pressed.
Step 7: Keep it fast
Web games run on phones and old laptops, so a few habits matter early.
- Draw fewer things. MDN's WebGL advice is that "batching draw calls into fewer, larger draw calls will generally improve performance." For many copies of one object, such as trees or coins, use
InstancedMesh. - Cap the pixel ratio. A phone with a 3x screen means nine times the pixels. The starter code caps it at 2 as a compromise.
- Clean up. Three.js does not free GPU memory for you. When you remove something for good, call
dispose()on its geometry, material and textures (how to dispose of objects). - Shrink your models. The glTF Transform command-line tool can compress a model in one step.
Step 8: Publish it
Build the game with a relative base path, so it works inside another site's page:
npx vite build --base=./That writes a dist folder of plain files. Any static host will serve it. These limits were checked in November 2026.
| Where | Cost | Limits to know |
|---|---|---|
| itch.io | Free to upload | Zip the dist folder. Up to 1,000 files and 500 MB extracted |
| GitHub Pages | Free | Sites up to 1 GB, soft limit of 100 GB of bandwidth a month |
| Cloudflare Pages | Free plan | Up to 20,000 files, 25 MiB per file |
| Vercel | Free Hobby plan | The terms limit Hobby to "personal or non-commercial use" |
| CrazyGames | Web game portal | 250 MB total, and an initial download of 50 MB or less |
For a first game, itch.io is the easiest: zip, upload, tick the box that says it runs in the browser, and share the link.
Multiplayer, briefly
Once the single-player game is fun, there are well-trodden ways to add other players. Colyseus is an open-source multiplayer framework you can host yourself. Socket.IO is a general library for real-time messages. PeerJS connects players directly to each other without a game server. Multiplayer multiplies the work, so finish the solo version first.
Old tutorials and AI answers: what has changed
Three.js moves fast, and both search results and AI models lean on older code. These are the changes most likely to trip you up, all from the official migration guide:
Clockis deprecated since r183. UseTimer, as the starter game does.RGBELoaderis nowHDRLoader(r180).PointerLockControls.getObject()was removed (r168). Usecontrols.object.- Light intensity changed in r155. Lights copied from old tutorials can look far too dark or too bright.
- The manual moved. Links to
threejs.org/manual/en/...no longer work. Pages now live under/manual/pages/.
You will also see WebGPU mentioned. It is the newer graphics system, and Three.js has a WebGPURenderer that falls back to WebGL when needed. The manual still calls that renderer "experimental" and says the classic WebGLRenderer remains "the recommended choice for pure WebGL 2 applications." Start with WebGLRenderer, as this tutorial does.
Building it with an AI coding tool
You can hand most of this work to an AI agent. Two things make it go well: tell it the exact version, and make it work in small steps. Here is a prompt to start a new game from the code above.
We are building a browser game with three.js r187 (npm three@0.187.0) and Vite. No other libraries unless I agree.
Version rules:
- Use THREE.Timer, not THREE.Clock (deprecated since r183).
- Use renderer.setAnimationLoop for the game loop.
- Use WebGLRenderer. Import addons from 'three/addons/...'.
- If you are unsure an API exists in r187, check the docs at threejs.org/docs before using it.
The game: [one or two sentences].
Start from the attached main.js. Add one feature at a time, in this order:
1. [first feature]
2. [second feature]
3. [third feature]
After each feature, run the game in the browser, check the console for errors, and tell me how to test it myself. Do not start the next feature until I say so.Which tool to give that prompt to is its own decision. We compare the options in which harness is best for game building and the models behind them in Gemini vs Claude vs ChatGPT for game building. For the bigger picture, from story and characters to scope, see how to build a game with AI.
Where to go from here
You have a game loop, a goal and a way to publish. The next version is up to you: swap the capsule for a character, turn the field into a level, add something that chases the player. The official examples and the manual's "Making a Game" tutorial are the best places to see how the pieces fit.
It is also a good moment to show people what you are making. A playable link and a page that explains the idea will get you feedback long before the game is finished.