If you want to build 3D games that run directly in the browser, Three.js (3JS) is one of the best libraries you can start with. It sits on top of WebGL and gives you a clean JavaScript API for creating 3D scenes, models, lights, and animations โ perfect for browser-based games.
In this article, youโll learn step by step how to create a simple 3D game with Three.js, from project setup to basic gameplay.
You can paste this article directly into WordPress (Gutenberg or Classic Editor) and add โCodeโ blocks where needed.
What Is Three.js and Why Use It for Games?
Three.js is an open-source JavaScript library that makes it much easier to work with WebGL. Instead of writing low-level GPU code, you can use Three.js to:
- Create 3D scenes, cameras, and lighting
- Add models, textures, and materials
- Animate objects and cameras
- Build interactive 3D experiences and games
For game development, Three.js is great because:
- It runs entirely in the browser (no plugins or installs needed)
- It uses JavaScript, so it fits naturally into modern web stacks
- It has a large community and many examples
- It works well with build tools like Vite, Webpack, or frameworks like React
In this tutorial, weโll create a simple 3D โcollect the cubeโ game where:
- You control a player cube with the keyboard
- You move around a plane
- You collect randomly placed โcoinsโ
- Your score updates when you collect a coin
Step 1: Project Setup (HTML + Three.js via CDN)
For a simple setup, you donโt need any bundler. You can use a plain HTML file and include Three.js from a CDN.
Create a file called index.html and add the following base structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Three.js Game Demo</title>
<style>
body {
margin: 0;
overflow: hidden;
font-family: Arial, sans-serif;
background: #111;
color: white;
}
#score {
position: fixed;
top: 10px;
left: 10px;
padding: 8px 12px;
background: rgba(0,0,0,0.5);
border-radius: 4px;
z-index: 10;
}
</style>
</head>
<body>
<div id="score">Score: 0</div>
<!-- Three.js CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r152/three.min.js"></script>
<!-- Our game script -->
<script src="game.js"></script>
</body>
</html>
Now create a game.js file in the same folder. This is where all of our Three.js game logic will go.
Step 2: Create the Scene, Camera, and Renderer
In game.js, start by creating the scene, camera, and renderer. These are the core pieces of every Three.js project.
// game.js
let scene, camera, renderer;
let player, plane;
let coins = [];
let score = 0;
const scoreEl = document.getElementById('score');
init();
animate();
function init() {
// Create scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x202020);
// Create camera
const fov = 60;
const aspect = window.innerWidth / window.innerHeight;
const near = 0.1;
const far = 1000;
camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
camera.position.set(0, 10, 15);
camera.lookAt(0, 0, 0);
// Create renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Handle window resize
window.addEventListener('resize', onWindowResize);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
At this point, the page is blank but the Three.js renderer is created and ready.
Step 3: Add Lighting, a Floor, and the Player
Now letโs add:
- A plane as the floor
- A player cube that weโll control
- Some basic lighting so we can see everything
Add this inside init() after the renderer setup:
// Lights
const ambientLight = new THREE.AmbientLight(0xffffff, 0.4);
scene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.8);
dirLight.position.set(5, 10, 7);
scene.add(dirLight);
// Floor (plane)
const planeGeom = new THREE.PlaneGeometry(40, 40);
const planeMat = new THREE.MeshStandardMaterial({ color: 0x333333 });
plane = new THREE.Mesh(planeGeom, planeMat);
plane.rotation.x = -Math.PI / 2;
scene.add(plane);
// Player (cube)
const playerGeom = new THREE.BoxGeometry(1, 1, 1);
const playerMat = new THREE.MeshStandardMaterial({ color: 0x00ff00 });
player = new THREE.Mesh(playerGeom, playerMat);
player.position.y = 0.5;
scene.add(player);
Now we have a visible 3D environment.
Step 4: Add Collectible Coins
Letโs add a simple โcoinโ object โ a small sphere placed randomly on the floor. When the player touches a coin, the score will increase.
Add this helper function below init():
function spawnCoin() {
const coinGeom = new THREE.SphereGeometry(0.4, 16, 16);
const coinMat = new THREE.MeshStandardMaterial({ color: 0xffcc00 });
const coin = new THREE.Mesh(coinGeom, coinMat);
// Random position on the plane
const range = 15;
coin.position.set(
(Math.random() - 0.5) * 2 * range,
0.4,
(Math.random() - 0.5) * 2 * range
);
scene.add(coin);
coins.push(coin);
}
Call this function a few times at the end of init():
// Spawn initial coins
for (let i = 0; i < 5; i++) {
spawnCoin();
}
Step 5: Add Keyboard Controls to Move the Player
Now we need to let the user control the player cube. Weโll use the WASD keys to move around the plane.
At the top of game.js, add:
const keys = {};
document.addEventListener('keydown', e => keys[e.key.toLowerCase()] = true);
document.addEventListener('keyup', e => keys[e.key.toLowerCase()] = false);
Then create a function to handle movement:
function updatePlayer(delta) {
const speed = 6; // units per second
let moveX = 0;
let moveZ = 0;
if (keys['w'] || keys['arrowup']) moveZ -= 1;
if (keys['s'] || keys['arrowdown']) moveZ += 1;
if (keys['a'] || keys['arrowleft']) moveX -= 1;
if (keys['d'] || keys['arrowright']) moveX += 1;
// Normalize diagonal movement
const len = Math.hypot(moveX, moveZ) || 1;
moveX /= len;
moveZ /= len;
player.position.x += moveX * speed * delta;
player.position.z += moveZ * speed * delta;
// Keep player within bounds of the plane
const limit = 18;
player.position.x = Math.max(-limit, Math.min(limit, player.position.x));
player.position.z = Math.max(-limit, Math.min(limit, player.position.z));
}
Step 6: Detect Collisions Between Player and Coins
Weโll implement a simple bounding distance check between the player and each coin.
Add this function:
function checkCollisions() {
const playerPos = player.position;
coins = coins.filter(coin => {
const dist = playerPos.distanceTo(coin.position);
if (dist < 1.0) {
// Collected
scene.remove(coin);
score++;
scoreEl.textContent = `Score: ${score}`;
spawnCoin(); // spawn a new coin
return false;
}
return true;
});
}
Step 7: The Game Loop (Animation + Game Logic)
Now we need a loop that runs every frame:
- Updates the player
- Checks collisions
- Renders the scene
Add this at the bottom of game.js (we already called animate() earlier):
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = clock.getDelta(); // time since last frame
updatePlayer(delta);
checkCollisions();
renderer.render(scene, camera);
}
Now you have a basic Three.js game:
- Move with W/A/S/D or arrow keys
- Collect yellow spheres
- Score updates in the top-left corner
Step 8: Enhancing Your Three.js Game (Ideas)
Once the basics are working, you can extend your game:
- Add obstacles or enemies โ cubes that move and cause โgame overโ on collision
- Add a timer โ collect as many coins as possible before time runs out
- Add sound effects โ play audio when collecting a coin
- Use real 3D models โ replace the player cube with a character model
- Add a UI overlay โ use HTML/CSS for menus, HUD, and game over screens
Three.js is flexible enough for many genres:
- Racing games
- Platformers
- Endless runners
- Space shooters
- Puzzle and adventure games
SEO Tips for Posting This on WordPress
To make this article more SEO-friendly on your WordPress site:
- Use a keyword-rich title
Example:
โHow to Create a 3D Browser Game with Three.js (3JS) โ Step-by-Step Tutorialโ - Include target keywords naturally
- three.js game tutorial
- how to create game with Three.js
- 3JS game development
- 3D game in JavaScript
- Add proper headings (H2, H3) in WordPress
- Each section in this article can be an H2 or H3 for better structure.
- Add a meta description (via SEO plugin like Yoast or Rank Math)
Example:
โLearn how to create a 3D game with Three.js (3JS) in JavaScript. This step-by-step guide covers project setup, movement, collision detection, and basic game logic for web-based 3D games.โ - Use Code Blocks for Snippets
In Gutenberg, use the โCodeโ block for JavaScript and HTML snippets. - Add internal and external links
- Link to other JavaScript tutorials on your site
- Link to the official Three.js docs: https://threejs.org/docs
Conclusion
Building a 3D game with Three.js (3JS) is a great way to learn both JavaScript and real-time graphics. With just a simple setup and a few core conceptsโscene, camera, renderer, objects, input handling, and basic collisionโyou can create interactive 3D experiences that run in any modern browser.
From here, you can:
- Add more objects and levels
- Integrate models from Blender
- Add physics via libraries like Cannon.js or Ammo.js
- Explore WebXR for VR/AR games