<!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;
}
canvas {
display: block;
}
#crosshair {
position: absolute;
top: 50%;
left: 50%;
width: 20px;
height: 20px;
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;
left: 9px;
top: 0;
}
#crosshair::after {
width: 20px;
height: 2px;
left: 0;
top: 9px;
}
#hud {
position: absolute;
bottom: 20px;
left: 20px;
color: white;
user-select: none;
}
#ammo {
font-size: 24px;
margin-bottom: 10px;
}
#health-bar {
width: 200px;
height: 20px;
background-color: rgba(0, 0, 0, 0.5);
border-radius: 10px;
overflow: hidden;
}
#health-fill {
height: 100%;
width: 100%;
background-color: #2ecc71;
transition: width 0.3s;
}
#reload-message {
position: absolute;
top: 70%;
left: 50%;
transform: translateX(-50%);
color: white;
font-size: 20px;
opacity: 0;
transition: opacity 0.3s;
}
#game-ui {
position: absolute;
top: 20px;
right: 20px;
color: white;
user-select: none;
}
#bullets {
position: absolute;
bottom: 20px;
right: 20px;
display: flex;
gap: 2px;
}
.bullet {
width: 5px;
height: 15px;
background-color: #f39c12;
border-radius: 2px;
}
#hit-marker {
position: absolute;
top: 50%;
left: 50%;
width: 30px;
height: 30px;
transform: translate(-50%, -50%);
opacity: 0;
transition: opacity 0.15s;
pointer-events: none;
}
#hit-marker::before,
#hit-marker::after {
content: '';
position: absolute;
background-color: rgba(255, 0, 0, 0.8);
}
#hit-marker::before {
width: 2px;
height: 30px;
left: 14px;
top: 0;
transform: rotate(45deg);
}
#hit-marker::after {
width: 30px;
height: 2px;
left: 0;
top: 14px;
transform: rotate(45deg);
}
</style>
</head>
<body>
<div id="crosshair"></div>
<div id="hit-marker"></div>
<div id="hud">
<div id="ammo">Ammo: <span id="ammo-count">10</span>/10</div>
<div id="health-bar">
<div id="health-fill"></div>
</div>
</div>
<div id="bullets"></div>
<div id="reload-message">Reloading...</div>
<div id="game-ui">Score: <span id="score">0</span></div>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/examples/js/controls/PointerLockControls.js"></script>
<script>
// Game variables
let camera, scene, renderer, controls;
let moveForward = false;
let moveBackward = false;
let moveLeft = false;
let moveRight = false;
let canJump = false;
let prevTime = performance.now();
let velocity = new THREE.Vector3();
let direction = new THREE.Vector3();
let gun, gunLight;
let ammo = 10;
let maxAmmo = 10;
let reloading = false;
let health = 100;
let score = 0;
let targets = [];
let bullets = [];
let bulletSpeed = 10;
let raycaster = new THREE.Raycaster();
let mouse = new THREE.Vector2();
// Initialize the game
init();
animate();
function init() {
// Setup scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x87ceeb);
scene.fog = new THREE.Fog(0x87ceeb, 0, 500);
// Setup camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.y = 1.7; // Player height
// Setup lights
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 0.5).normalize();
scene.add(directionalLight);
// Create floor
const floorGeometry = new THREE.PlaneGeometry(100, 100, 10, 10);
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x999999,
roughness: 1.0,
metalness: 0.0
});
const floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
// Create walls
createWalls();
// Create targets
createTargets();
// Create gun
createGun();
// Setup pointer lock controls
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
controls = new THREE.PointerLockControls(camera, document.body);
// Event listeners for controls
document.addEventListener('click', function() {
controls.lock();
});
controls.addEventListener('lock', function() {
document.getElementById('crosshair').style.display = 'block';
});
controls.addEventListener('unlock', function() {
document.getElementById('crosshair').style.display = 'none';
});
document.addEventListener('keydown', onKeyDown);
document.addEventListener('keyup', onKeyUp);
document.addEventListener('mousedown', onMouseDown);
// Create bullet indicators
updateBulletDisplay();
// Window resize handler
window.addEventListener('resize', onWindowResize);
}
function createWalls() {
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0x8b4513,
roughness: 0.8,
metalness: 0.2
});
// Back wall
const backWallGeometry = new THREE.BoxGeometry(100, 10, 1);
const backWall = new THREE.Mesh(backWallGeometry, wallMaterial);
backWall.position.set(0, 5, -50);
scene.add(backWall);
// Front wall
const frontWallGeometry = new THREE.BoxGeometry(100, 10, 1);
const frontWall = new THREE.Mesh(frontWallGeometry, wallMaterial);
frontWall.position.set(0, 5, 50);
scene.add(frontWall);
// Left wall
const leftWallGeometry = new THREE.BoxGeometry(1, 10, 100);
const leftWall = new THREE.Mesh(leftWallGeometry, wallMaterial);
leftWall.position.set(-50, 5, 0);
scene.add(leftWall);
// Right wall
const rightWallGeometry = new THREE.BoxGeometry(1, 10, 100);
const rightWall = new THREE.Mesh(rightWallGeometry, wallMaterial);
rightWall.position.set(50, 5, 0);
scene.add(rightWall);
// Create some obstacles
for (let i = 0; i < 10; i++) {
const boxGeometry = new THREE.BoxGeometry(2, 3, 2);
const boxMaterial = new THREE.MeshStandardMaterial({
color: 0x555555,
roughness: 0.7,
metalness: 0.3
});
const box = new THREE.Mesh(boxGeometry, boxMaterial);
box.position.set(
Math.random() * 80 - 40,
1.5,
Math.random() * 80 - 40
);
scene.add(box);
}
}
function createTargets() {
const targetGeometry = new THREE.BoxGeometry(2, 2, 0.5);
const targetMaterial = new THREE.MeshStandardMaterial({
color: 0xff0000,
roughness: 0.5,
metalness: 0.5
});
for (let i = 0; i < 15; i++) {
const target = new THREE.Mesh(targetGeometry, targetMaterial);
let x, z;
// Ensure targets are not too close to the player
do {
x = Math.random() * 80 - 40;
z = Math.random() * 80 - 40;
} while (Math.sqrt(x * x + z * z) < 10);
target.position.set(x, 1.5, z);
target.userData = { health: 100, isTarget: true };
scene.add(target);
targets.push(target);
}
}
function createGun() {
// Create a simple gun model
const gunMaterial = new THREE.MeshStandardMaterial({
color: 0x333333,
roughness: 0.5,
metalness: 0.7
});
gun = new THREE.Group();
// Gun barrel
const barrelGeometry = new THREE.BoxGeometry(0.1, 0.1, 0.5);
const barrel = new THREE.Mesh(barrelGeometry, gunMaterial);
barrel.position.set(0, 0, -0.25);
gun.add(barrel);
// Gun body
const bodyGeometry = new THREE.BoxGeometry(0.2, 0.3, 0.2);
const body = new THREE.Mesh(bodyGeometry, gunMaterial);
body.position.set(0, -0.15, -0.05);
gun.add(body);
// Gun handle
const handleGeometry = new THREE.BoxGeometry(0.15, 0.4, 0.15);
const handle = new THREE.Mesh(handleGeometry, gunMaterial);
handle.position.set(0, -0.4, 0);
gun.add(handle);
// Position the gun in front of the camera
gun.position.set(0.3, -0.3, -0.5);
camera.add(gun);
scene.add(camera);
// Add a light at the end of the gun for muzzle flash
gunLight = new THREE.PointLight(0xffff00, 0, 2);
gunLight.position.set(0, 0, -0.5);
gun.add(gunLight);
}
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 'Space':
if (canJump === true) velocity.y += 10;
canJump = false;
break;
case 'KeyR':
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 onMouseDown(event) {
if (controls.isLocked && !reloading) {
if (event.button === 0) { // Left mouse button
shoot();
}
}
}
function shoot() {
if (ammo <= 0) {
reload();
return;
}
// Decrease ammo
ammo--;
updateAmmoDisplay();
updateBulletDisplay();
// Muzzle flash effect
gunLight.intensity = 3;
setTimeout(() => {
gunLight.intensity = 0;
}, 50);
// Gun recoil effect
gun.position.z += 0.05;
gun.rotation.x -= 0.1;
setTimeout(() => {
gun.position.z = -0.5;
gun.rotation.x = 0;
}, 100);
// Create bullet visual
const bulletGeometry = new THREE.SphereGeometry(0.05, 8, 8);
const bulletMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00 });
const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial);
// Position bullet at the end of the gun barrel
bullet.position.set(
camera.position.x,
camera.position.y,
camera.position.z
);
// Set bullet direction to camera facing direction
const direction = new THREE.Vector3();
camera.getWorldDirection(direction);
bullet.userData = {
velocity: direction.multiplyScalar(bulletSpeed),
timeCreated: Date.now()
};
scene.add(bullet);
bullets.push(bullet);
// Check for hit using raycaster
raycaster.setFromCamera(new THREE.Vector2(), camera);
const intersects = raycaster.intersectObjects(targets);
if (intersects.length > 0) {
const hit = intersects[0];
if (hit.object.userData.isTarget) {
hit.object.userData.health -= 50;
if (hit.object.userData.health <= 0) {
// Target destroyed
score += 100;
document.getElementById('score').textContent = score;
scene.remove(hit.object);
targets.splice(targets.indexOf(hit.object), 1);
} else {
// Target hit but not destroyed
hit.object.material.color.set(0xff0000 * hit.object.userData.health / 100);
}
// Show hit marker
const hitMarker = document.getElementById('hit-marker');
hitMarker.style.opacity = 1;
setTimeout(() => {
hitMarker.style.opacity = 0;
}, 150);
}
}
}
function reload() {
if (reloading || ammo === maxAmmo) return;
reloading = true;
const reloadMessage = document.getElementById('reload-message');
reloadMessage.style.opacity = 1;
// Gun reloading animation
gun.position.z = -0.3;
gun.rotation.x = -0.5;
setTimeout(() => {
ammo = maxAmmo;
updateAmmoDisplay();
updateBulletDisplay();
reloading = false;
reloadMessage.style.opacity = 0;
gun.position.z = -0.5;
gun.rotation.x = 0;
}, 1500);
}
function updateAmmoDisplay() {
document.getElementById('ammo-count').textContent = ammo;
}
function updateBulletDisplay() {
const bulletsContainer = document.getElementById('bullets');
bulletsContainer.innerHTML = '';
for (let i = 0; i < maxAmmo; i++) {
const bullet = document.createElement('div');
bullet.className = 'bullet';
if (i >= ammo) {
bullet.style.backgroundColor = '#555';
}
bulletsContainer.appendChild(bullet);
}
}
function updateHealthDisplay() {
document.getElementById('health-fill').style.width = health + '%';
// Change color based on health
let color;
if (health > 60) {
color = '#2ecc71'; // Green
} else if (health > 30) {
color = '#f39c12'; // Orange
} else {
color = '#e74c3c'; // Red
}
document.getElementById('health-fill').style.backgroundColor = color;
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
if (controls.isLocked === true) {
const time = performance.now();
const delta = (time - prevTime) / 1000;
// Apply gravity
velocity.y -= 9.8 * delta;
// Move player based on controls
direction.z = Number(moveForward) - Number(moveBackward);
direction.x = Number(moveRight) - Number(moveLeft);
direction.normalize();
if (moveForward || moveBackward) velocity.z -= direction.z * 20.0 * delta;
if (moveLeft || moveRight) velocity.x -= direction.x * 20.0 * delta;
// Apply damping
velocity.x -= velocity.x * 10.0 * delta;
velocity.z -= velocity.z * 10.0 * delta;
// Move player
controls.moveRight(-velocity.x * delta);
controls.moveForward(-velocity.z * delta);
// Simple collision detection with ground
if (camera.position.y < 1.7) {
velocity.y = 0;
camera.position.y = 1.7;
canJump = true;
} else {
camera.position.y += velocity.y * delta;
}
// Simple collision detection with walls
if (camera.position.x > 49) camera.position.x = 49;
if (camera.position.x < -49) camera.position.x = -49;
if (camera.position.z > 49) camera.position.z = 49;
if (camera.position.z < -49) camera.position.z = -49;
// Update bullets
updateBullets(delta);
prevTime = time;
}
renderer.render(scene, camera);
}
function updateBullets(delta) {
// Update bullet positions
for (let i = bullets.length - 1; i >= 0; i--) {
const bullet = bullets[i];
bullet.position.add(bullet.userData.velocity.clone().multiplyScalar(delta));
// Remove bullets after 5 seconds or if they hit something
if (Date.now() - bullet.userData.timeCreated > 5000) {
scene.remove(bullet);
bullets.splice(i, 1);
}
}
}
</script>
</body>
</html>
Would you like me to explain or break down this code?