3D FPS Game with Three.js
Here's a complete single-file 3D FPS game using Three.js with WASD movement, shooting mechanics, a crosshair, and a simple HUD system:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>3D FPS Game</title>
<style>
body {
margin: 0;
overflow: hidden;
font-family: 'Arial', sans-serif;
background-color: #000;
color: white;
}
#game-container {
position: relative;
width: 100vw;
height: 100vh;
}
#hud {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 20px;
box-sizing: border-box;
}
#crosshair {
position: absolute;
top: 50%;
left: 50%;
width: 30px;
height: 30px;
transform: translate(-50%, -50%);
pointer-events: none;
}
#crosshair::before, #crosshair::after {
content: '';
position: absolute;
background-color: rgba(255, 255, 255, 0.8);
}
#crosshair::before {
width: 2px;
height: 20px;
top: 5px;
left: 14px;
}
#crosshair::after {
width: 20px;
height: 2px;
top: 14px;
left: 5px;
}
#ammo-display {
background-color: rgba(0, 0, 0, 0.5);
padding: 10px 20px;
border-radius: 5px;
font-size: 18px;
align-self: flex-end;
margin: 20px;
}
#health-bar {
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 5px;
width: 200px;
margin: 20px;
}
#health-fill {
height: 20px;
background-color: #4CAF50;
border-radius: 5px;
width: 100%;
transition: width 0.3s;
}
#gun {
position: absolute;
bottom: 20px;
right: 50%;
transform: translateX(50%);
width: 200px;
height: 100px;
background-color: rgba(50, 50, 50, 0.7);
border-radius: 10px;
display: flex;
justify-content: center;
align-items: center;
pointer-events: none;
}
#gun::after {
content: '';
width: 30px;
height: 50px;
background-color: rgba(100, 100, 100, 0.9);
position: absolute;
right: 10px;
border-radius: 5px;
}
#hit-marker {
position: absolute;
top: 50%;
left: 50%;
width: 50px;
height: 50px;
background-color: rgba(255, 0, 0, 0.3);
border-radius: 50%;
transform: translate(-50%, -50%);
display: none;
pointer-events: none;
}
#game-over {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.8);
display: none;
flex-direction: column;
justify-content: center;
align-items: center;
font-size: 48px;
color: red;
pointer-events: none;
}
#restart-btn {
margin-top: 20px;
padding: 10px 20px;
font-size: 24px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
pointer-events: auto;
}
#restart-btn:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div id="game-container">
<div id="hud">
<div id="health-bar">
<div id="health-fill"></div>
</div>
<div id="ammo-display">Ammo: 30/∞</div>
<div id="gun"></div>
</div>
<div id="crosshair"></div>
<div id="hit-marker"></div>
<div id="game-over">
GAME OVER
<button id="restart-btn">Restart</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<script>
// Game variables
let scene, camera, renderer, controls;
let player, gun;
let bullets = [];
let enemies = [];
let health = 100;
let ammo = 30;
let maxAmmo = 30;
let isShooting = false;
let canShoot = true;
let gameOver = false;
let mouseX = 0, mouseY = 0;
let moveForward = false, moveBackward = false, moveLeft = false, moveRight = false;
let velocity = new THREE.Vector3();
let direction = new THREE.Vector3();
let clock = new THREE.Clock();
let raycaster = new THREE.Raycaster();
let mouse = new THREE.Vector2();
// Initialize the game
init();
animate();
function init() {
// Create scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x87CEEB); // Sky blue
// Create camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.y = 1.6; // Player height
// Create renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.getElementById('game-container').prepend(renderer.domElement);
// Add ambient light
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
// Add directional light
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 1);
directionalLight.castShadow = true;
scene.add(directionalLight);
// Create ground
const groundGeometry = new THREE.PlaneGeometry(100, 100);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x3a5f0b,
roughness: 0.8,
metalness: 0.2
});
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
// Create walls
const wallGeometry = new THREE.BoxGeometry(100, 10, 1);
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0x5a3a22,
roughness: 0.7
});
// Front wall
const frontWall = new THREE.Mesh(wallGeometry, wallMaterial);
frontWall.position.set(0, 5, -50);
scene.add(frontWall);
// Back wall
const backWall = new THREE.Mesh(wallGeometry, wallMaterial);
backWall.position.set(0, 5, 50);
scene.add(backWall);
// Left wall
const leftWall = new THREE.Mesh(wallGeometry, wallMaterial);
leftWall.rotation.y = Math.PI / 2;
leftWall.position.set(-50, 5, 0);
scene.add(leftWall);
// Right wall
const rightWall = new THREE.Mesh(wallGeometry, wallMaterial);
rightWall.rotation.y = Math.PI / 2;
rightWall.position.set(50, 5, 0);
scene.add(rightWall);
// Create player
player = new THREE.Object3D();
player.position.set(0, 1.6, 0);
scene.add(player);
// Create gun
gun = new THREE.Object3D();
gun.position.set(0.5, -0.3, -1);
player.add(gun);
// Create some targets
createTargets(10);
// Event listeners
window.addEventListener('resize', onWindowResize);
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mousedown', onMouseDown);
document.addEventListener('mouseup', onMouseUp);
document.addEventListener('keydown', onKeyDown);
document.addEventListener('keyup', onKeyUp);
document.getElementById('restart-btn').addEventListener('click', restartGame);
// Update HUD
updateHUD();
}
function createTargets(count) {
const targetGeometry = new THREE.BoxGeometry(1, 1, 0.2);
const targetMaterial = new THREE.MeshStandardMaterial({
color: 0xff0000,
roughness: 0.5
});
for (let i = 0; i < count; i++) {
const target = new THREE.Mesh(targetGeometry, targetMaterial);
target.position.set(
Math.random() * 80 - 40,
1 + Math.random() * 3,
Math.random() * 80 - 40
);
target.userData = { health: 3 };
scene.add(target);
enemies.push(target);
}
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onMouseMove(event) {
mouseX = (event.clientX / window.innerWidth) * 2 - 1;
mouseY = -(event.clientY / window.innerHeight) * 2 + 1;
// Calculate camera rotation based on mouse position
player.rotation.y = mouseX * Math.PI / 4;
camera.rotation.x = mouseY * Math.PI / 8;
}
function onMouseDown(event) {
if (event.button === 0 && !gameOver) { // Left mouse button
isShooting = true;
if (canShoot && ammo > 0) {
shoot();
}
}
}
function onMouseUp(event) {
if (event.button === 0) { // Left mouse button
isShooting = false;
}
}
function onKeyDown(event) {
switch (event.code) {
case 'KeyW':
moveForward = true;
break;
case 'KeyA':
moveLeft = true;
break;
case 'KeyS':
moveBackward = true;
break;
case 'KeyD':
moveRight = true;
break;
case 'KeyR':
if (ammo < maxAmmo && !gameOver) {
reload();
}
break;
}
}
function onKeyUp(event) {
switch (event.code) {
case 'KeyW':
moveForward = false;
break;
case 'KeyA':
moveLeft = false;
break;
case 'KeyS':
moveBackward = false;
break;
case 'KeyD':
moveRight = false;
break;
}
}
function shoot() {
if (ammo <= 0 || gameOver) return;
ammo--;
canShoot = false;
updateHUD();
// Create bullet
const bullet = new THREE.Object3D();
bullet.position.copy(player.position);
bullet.position.y -= 0.2; // Lower the bullet origin
bullet.userData = {
direction: new THREE.Vector3(),
speed: 0.5
};
// Get the direction the player is facing
player.getWorldDirection(bullet.userData.direction);
// Add bullet to scene
scene.add(bullet);
bullets.push(bullet);
// Visual effect for shooting
const hitMarker = document.getElementById('hit-marker');
hitMarker.style.display = 'block';
setTimeout(() => {
hitMarker.style.display = 'none';
}, 100);
// Gun recoil animation
const gunElement = document.getElementById('gun');
gunElement.style.transform = 'translateX(50%) translateY(10px)';
setTimeout(() => {
gunElement.style.transform = 'translateX(50%)';
}, 100);
// Shoot cooldown
setTimeout(() => {
canShoot = true;
}, 100);
}
function reload() {
ammo = maxAmmo;
updateHUD();
}
function updateHUD() {
document.getElementById('ammo-display').textContent = `Ammo: ${ammo}/${maxAmmo}`;
document.getElementById('health-fill').style.width = `${health}%`;
if (health <= 0 && !gameOver) {
gameOver = true;
document.getElementById('game-over').style.display = 'flex';
}
}
function restartGame() {
// Reset game state
health = 100;
ammo = maxAmmo;
gameOver = false;
bullets = [];
enemies = [];
// Clear existing enemies
scene.children = scene.children.filter(child => {
return !child.userData || !child.userData.health;
});
// Create new targets
createTargets(10);
// Reset player position
player.position.set(0, 1.6, 0);
camera.rotation.x = 0;
player.rotation.y = 0;
// Hide game over screen
document.getElementById('game-over').style.display = 'none';
// Update HUD
updateHUD();
}
function animate() {
requestAnimationFrame(animate);
if (gameOver) return;
const delta = clock.getDelta();
// Player movement
velocity.x = 0;
velocity.z = 0;
if (moveForward) velocity.z -= 5 * delta;
if (moveBackward) velocity.z += 5 * delta;
if (moveLeft) velocity.x -= 5 * delta;
if (moveRight) velocity.x += 5 * delta;
// Apply movement
direction.z = velocity.z;
direction.x = velocity.x;
direction.applyQuaternion(player.quaternion);
// Check for collisions
const newPosition = player.position.clone().add(direction);
// Simple collision detection with walls
if (Math.abs(newPosition.x) < 45 && Math.abs(newPosition.z) < 45) {
player.position.add(direction);
}
// Update camera position to follow player
camera.position.copy(player.position);
camera.position.y += 0.5; // Slightly above player
// Update bullets
for (let i = bullets.length - 1; i >= 0; i--) {
const bullet = bullets[i];
bullet.position.add(bullet.userData.direction.clone().multiplyScalar(bullet.userData.speed));
// Check if bullet is out of bounds
if (Math.abs(bullet.position.x) > 50 ||
Math.abs(bullet.position.y) > 50 ||
Math.abs(bullet.position.z) > 50) {
scene.remove(bullet);
bullets.splice(i, 1);
continue;
}
// Check for collisions with enemies
raycaster.set(bullet.position, bullet.userData.direction);
const intersects = raycaster.intersectObjects(enemies);
if (intersects.length > 0) {
const enemy = intersects[0].object;
enemy.userData.health--;
if (enemy.userData.health <= 0) {
scene.remove(enemy);
enemies = enemies.filter(e => e !== enemy);
} else {
// Visual feedback for hit
enemy.material.color.setHex(0xffff00);
setTimeout(() => {
enemy.material.color.setHex(0xff0000);
}, 100);
}
scene.remove(bullet);
bullets.splice(i, 1);
}
}
// Auto-shooting
if (isShooting && canShoot && ammo > 0) {
shoot();
}
// Render scene
renderer.render(scene, camera);
}
</script>
</body>
</html>
Features:
-
Movement Controls:
- WASD keys for movement
- Mouse look around
-
Shooting Mechanics:
- Left mouse button to shoot
- R key to reload
- Visual recoil effect
- Hit marker feedback
-
HUD System:
- Health bar
- Ammo counter
- Crosshair
- Gun model in the bottom center
-
Game Elements:
- Red targets to shoot at
- Simple collision detection
- Game over screen with restart button
-
Visual Effects:
- Hit markers
- Gun recoil animation
- Target color change when hit
To play, simply copy this entire code into an HTML file and open it in a modern browser. Use WASD to move, mouse to look around, and left-click to shoot. Press R to reload.