import React, { useEffect, useRef, useState } from 'react'; import * as THREE from 'three'; import { PointerLockControls } from 'three/examples/jsm/controls/PointerLockControls'; import { Gun, Bullet, Enemy, createFloor, createWalls, createLighting } from './gameComponents'; export default function FPSGame() { const containerRef = useRef(null); const [gameState, setGameState] = useState('start'); // start, playing, gameover, victory const [health, setHealth] = useState(100); const [ammo, setAmmo] = useState(30); const [score, setScore] = useState(0); const [enemiesKilled, setEnemiesKilled] = useState(0); // Game refs const sceneRef = useRef(null); const cameraRef = useRef(null); const rendererRef = useRef(null); const controlsRef = useRef(null); const clockRef = useRef(new THREE.Clock()); const playerRef = useRef({ height: 1.8, speed: 5.0, turnSpeed: 0.5, canJump: false, velocity: new THREE.Vector3(), direction: new THREE.Vector3(), position: new THREE.Vector3(0, 1.8, 0), }); const keysRef = useRef({ forward: false, backward: false, left: false, right: false, jump: false, shoot: false, }); const gameObjectsRef = useRef({ bullets: [], enemies: [], walls: [], floor: null, gun: null, }); // Initialize the game useEffect(() => { if (!containerRef.current) return; // Setup scene const scene = new THREE.Scene(); scene.background = new THREE.Color(0x1a2639); scene.fog = new THREE.Fog(0x1a2639, 10, 50); sceneRef.current = scene; // Setup camera const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); camera.position.copy(playerRef.current.position); cameraRef.current = camera; // Setup renderer const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); renderer.shadowMap.enabled = true; renderer.shadowMap.type = THREE.PCFSoftShadowMap; containerRef.current.appendChild(renderer.domElement); rendererRef.current = renderer; // Setup controls const controls = new PointerLockControls(camera, renderer.domElement); controlsRef.current = controls; scene.add(controls.getObject()); // Create environment gameObjectsRef.current.floor = createFloor(scene); gameObjectsRef.current.walls = createWalls(scene); createLighting(scene); // Create gun gameObjectsRef.current.gun = new Gun(scene, camera); // Create enemies for (let i = 0; i < 10; i++) { const enemy = new Enemy( scene, new THREE.Vector3( Math.random() * 40 - 20, 1, Math.random() * 40 - 20 ) ); gameObjectsRef.current.enemies.push(enemy); } // Event listeners const onKeyDown = (event) => { switch (event.code) { case 'ArrowUp': case 'KeyW': keysRef.current.forward = true; break; case 'ArrowLeft': case 'KeyA': keysRef.current.left = true; break; case 'ArrowDown': case 'KeyS': keysRef.current.backward = true; break; case 'ArrowRight': case 'KeyD': keysRef.current.right = true; break; case 'Space': keysRef.current.jump = true; break; } }; const onKeyUp = (event) => { switch (event.code) { case 'ArrowUp': case 'KeyW': keysRef.current.forward = false; break; case 'ArrowLeft': case 'KeyA': keysRef.current.left = false; break; case 'ArrowDown': case 'KeyS': keysRef.current.backward = false; break; case 'ArrowRight': case 'KeyD': keysRef.current.right = false; break; case 'Space': keysRef.current.jump = false; break; } }; const onMouseDown = () => { if (gameState === 'playing' && ammo > 0) { shoot(); } }; const onWindowResize = () => { cameraRef.current.aspect = window.innerWidth / window.innerHeight; cameraRef.current.updateProjectionMatrix(); rendererRef.current.setSize(window.innerWidth, window.innerHeight); }; document.addEventListener('keydown', onKeyDown); document.addEventListener('keyup', onKeyUp); document.addEventListener('mousedown', onMouseDown); window.addEventListener('resize', onWindowResize); // Start animation loop animate(); return () => { document.removeEventListener('keydown', onKeyDown); document.removeEventListener('keyup', onKeyUp); document.removeEventListener('mousedown', onMouseDown); window.removeEventListener('resize', onWindowResize); if (containerRef.current && rendererRef.current) { containerRef.current.removeChild(rendererRef.current.domElement); } // Dispose of Three.js resources if (rendererRef.current) { rendererRef.current.dispose(); } }; }, []); // Game state effect useEffect(() => { if (gameState === 'playing') { controlsRef.current.lock(); } else if (controlsRef.current) { controlsRef.current.unlock(); } const onLock = () => setGameState('playing'); const onUnlock = () => { if (gameState === 'playing') { setGameState('paused'); } }; if (controlsRef.current) { controlsRef.current.addEventListener('lock', onLock); controlsRef.current.addEventListener('unlock', onUnlock); } return () => { if (controlsRef.current) { controlsRef.current.removeEventListener('lock', onLock); controlsRef.current.removeEventListener('unlock', onUnlock); } }; }, [gameState]); // Shooting function const shoot = () => { if (ammo <= 0) return; setAmmo(prev => prev - 1); const bullet = new Bullet( sceneRef.current, cameraRef.current.position.clone(), cameraRef.current.getWorldDirection(new THREE.Vector3()) ); gameObjectsRef.current.bullets.push(bullet); // Add recoil effect cameraRef.current.position.y -= 0.05; setTimeout(() => { if (cameraRef.current) { cameraRef.current.position.y += 0.05; } }, 100); }; // Animation loop const animate = () => { requestAnimationFrame(animate); if (gameState !== 'playing') return; const delta = clockRef.current.getDelta(); // Update player movement if (controlsRef.current.isLocked) { playerRef.current.velocity.x -= playerRef.current.velocity.x * 10.0 * delta; playerRef.current.velocity.z -= playerRef.current.velocity.z * 10.0 * delta; playerRef.current.direction.z = Number(keysRef.current.forward) - Number(keysRef.current.backward); playerRef.current.direction.x = Number(keysRef.current.right) - Number(keysRef.current.left); playerRef.current.direction.normalize(); if (keysRef.current.forward || keysRef.current.backward) { playerRef.current.velocity.z -= playerRef.current.direction.z * playerRef.current.speed * delta; } if (keysRef.current.left || keysRef.current.right) { playerRef.current.velocity.x -= playerRef.current.direction.x * playerRef.current.speed * delta; } controlsRef.current.moveRight(-playerRef.current.velocity.x * delta); controlsRef.current.moveForward(-playerRef.current.velocity.z * delta); // Update player position reference playerRef.current.position.copy(controlsRef.current.getObject().position); } // Update bullets gameObjectsRef.current.bullets.forEach((bullet, index) => { bullet.update(delta); // Check for bullet collisions with enemies gameObjectsRef.current.enemies.forEach((enemy, enemyIndex) => { if (bullet.checkCollision(enemy.mesh.position, 1)) { // Remove bullet bullet.remove(); gameObjectsRef.current.bullets.splice(index, 1); // Damage enemy enemy.takeDamage(25); if (enemy.health <= 0) { // Remove enemy enemy.remove(); gameObjectsRef.current.enemies.splice(enemyIndex, 1); // Update score setScore(prev => prev + 100); setEnemiesKilled(prev => prev + 1); // Check for victory if (gameObjectsRef.current.enemies.length === 0) { setGameState('victory'); } } } }); // Remove bullets that have traveled too far if (bullet.distanceTraveled > 100) { bullet.remove(); gameObjectsRef.current.bullets.splice(index, 1); } }); // Update enemies gameObjectsRef.current.enemies.forEach(enemy => { enemy.update(delta, playerRef.current.position); // Check if enemy is close to player if (enemy.mesh.position.distanceTo(playerRef.current.position) < 2) { // Player takes damage setHealth(prev => { const newHealth = prev - 5; if (newHealth <= 0) { setGameState('gameover'); } return newHealth; }); // Push player back const pushDirection = new THREE.Vector3() .subVectors(playerRef.current.position, enemy.mesh.position) .normalize() .multiplyScalar(0.5); controlsRef.current.moveRight(pushDirection.x); controlsRef.current.moveForward(pushDirection.z); } }); // Update gun position if (gameObjectsRef.current.gun) { gameObjectsRef.current.gun.update(delta); } // Render scene rendererRef.current.render(sceneRef.current, cameraRef.current); }; // Handle game restart const restartGame = () => { // Reset game state setGameState('start'); setHealth(100); setAmmo(30); setScore(0); setEnemiesKilled(0); // Reset player position playerRef.current.position.set(0, 1.8, 0); controlsRef.current.getObject().position.copy(playerRef.current.position); // Remove all bullets gameObjectsRef.current.bullets.forEach(bullet => bullet.remove()); gameObjectsRef.current.bullets = []; // Remove all enemies gameObjectsRef.current.enemies.forEach(enemy => enemy.remove()); gameObjectsRef.current.enemies = []; // Create new enemies for (let i = 0; i < 10; i++) { const enemy = new Enemy( sceneRef.current, new THREE.Vector3( Math.random() * 40 - 20, 1, Math.random() * 40 - 20 ) ); gameObjectsRef.current.enemies.push(enemy); } }; // Render UI based on game state const renderUI = () => { switch (gameState) { case 'start': return (

Realistic FPS

Click to play. Use WASD to move, mouse to aim, and click to shoot.

); case 'paused': return (

Game Paused

Click to resume the game.

); case 'gameover': return (

Game Over

Score: {score}

Enemies Killed: {enemiesKilled}

); case 'victory': return (

Victory!

Score: {score}

Enemies Killed: {enemiesKilled}

); case 'playing': return ( <> {/* Crosshair */}
{/* HUD */}
{health}
{ammo}
Score: {score}
Enemies: {gameObjectsRef.current.enemies.length}
); default: return null; } }; return (
{renderUI()}
); } // Game components (would normally be in separate files) class Gun { constructor(scene, camera) { this.scene = scene; this.camera = camera; // Create gun model const gunGeometry = new THREE.BoxGeometry(0.1, 0.1, 0.5); const gunMaterial = new THREE.MeshStandardMaterial({ color: 0x3f4e63 }); this.mesh = new THREE.Mesh(gunGeometry, gunMaterial); // Create muzzle const muzzleGeometry = new THREE.CylinderGeometry(0.03, 0.03, 0.1, 8); const muzzleMaterial = new THREE.MeshStandardMaterial({ color: 0x222222 }); this.muzzle = new THREE.Mesh(muzzleGeometry, muzzleMaterial); this.muzzle.position.z = -0.3; this.muzzle.rotation.x = Math.PI / 2; this.mesh.add(this.muzzle); // Add gun to scene scene.add(this.mesh); // Set initial position this.update(0); } update(delta) { // Position gun in front of camera const cameraDirection = new THREE.Vector3(); this.camera.getWorldDirection(cameraDirection); const position = this.camera.position.clone(); position.add(cameraDirection.multiplyScalar(0.5)); position.y -= 0.2; this.mesh.position.copy(position); this.mesh.rotation.copy(this.camera.rotation); // Add slight bobbing effect when moving const time = Date.now() * 0.002; this.mesh.position.y += Math.sin(time * 4) * 0.01; this.mesh.position.x += Math.cos(time * 2) * 0.005; } } class Bullet { constructor(scene, position, direction) { this.scene = scene; this.direction = direction.normalize(); this.speed = 30; this.distanceTraveled = 0; // Create bullet const geometry = new THREE.SphereGeometry(0.05, 8, 8); const material = new THREE.MeshBasicMaterial({ color: 0xe9d985 }); this.mesh = new THREE.Mesh(geometry, material); this.mesh.position.copy(position); // Add bullet trail const trailGeometry = new THREE.CylinderGeometry(0.01, 0.01, 0.5, 8); const trailMaterial = new THREE.MeshBasicMaterial({ color: 0xe9d985, transparent: true, opacity: 0.5 }); this.trail = new THREE.Mesh(trailGeometry, trailMaterial); this.trail.rotation.x = Math.PI / 2; this.mesh.add(this.trail); scene.add(this.mesh); } update(delta) { const moveDistance = this.speed * delta; this.mesh.position.add(this.direction.clone().multiplyScalar(moveDistance)); this.distanceTraveled += moveDistance; } checkCollision(targetPosition, targetRadius) { return this.mesh.position.distanceTo(targetPosition) < targetRadius; } remove() { this.scene.remove(this.mesh); } } class Enemy { constructor(scene, position) { this.scene = scene; this.health = 100; this.speed = 2 + Math.random() * 2; // Create enemy const geometry = new THREE.CapsuleGeometry(0.5, 1, 4, 8); const material = new THREE.MeshStandardMaterial({ color: 0xc24d2c }); this.mesh = new THREE.Mesh(geometry, material); this.mesh.position.copy(position); // Create enemy head const headGeometry = new THREE.SphereGeometry(0.3, 16, 16); const headMaterial = new THREE.MeshStandardMaterial({ color: 0xc24d2c }); this.head = new THREE.Mesh(headGeometry, headMaterial); this.head.position.y = 0.9; this.mesh.add(this.head); // Create enemy eyes const eyeGeometry = new THREE.SphereGeometry(0.08, 8, 8); const eyeMaterial = new THREE.MeshStandardMaterial({ color: 0x000000 }); this.leftEye = new THREE.Mesh(eyeGeometry, eyeMaterial); this.leftEye.position.set(0.15, 0.1, 0.2); this.head.add(this.leftEye); this.rightEye = new THREE.Mesh(eyeGeometry, eyeMaterial); this.rightEye.position.set(-0.15, 0.1, 0.2); this.head.add(this.rightEye); scene.add(this.mesh); } update(delta, playerPosition) { // Move towards player const direction = new THREE.Vector3() .subVectors(playerPosition, this.mesh.position) .normalize(); // Keep enemy on the ground direction.y = 0; // Move enemy this.mesh.position.add(direction.multiplyScalar(this.speed * delta)); // Make enemy face player this.mesh.lookAt(new THREE.Vector3(playerPosition.x, this.mesh.position.y, playerPosition.z)); } takeDamage(amount) { this.health -= amount; // Visual feedback for damage this.mesh.material.color.setHex(0xff0000); setTimeout(() => { if (this.mesh.material) { this.mesh.material.color.setHex(0xc24d2c); } }, 100); } remove() { this.scene.remove(this.mesh); } } // Environment creation functions function createFloor(scene) { const geometry = new THREE.PlaneGeometry(100, 100); const material = new THREE.MeshStandardMaterial({ color: 0x3f4e63, roughness: 0.8, metalness: 0.2 }); const floor = new THREE.Mesh(geometry, material); floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor); return floor; } function createWalls(scene) { const walls = []; const wallMaterial = new THREE.MeshStandardMaterial({ color: 0x1a2639, roughness: 0.7, metalness: 0.2 }); // Create boundary walls const wallGeometries = [ new THREE.BoxGeometry(100, 5, 1), // North new THREE.BoxGeometry(100, 5, 1), // South new THREE.BoxGeometry(1, 5, 100), // East new THREE.BoxGeometry(1, 5, 100) // West ]; const wallPositions = [ [0, 2.5, -50], [0, 2.5, 50], [50, 2.5, 0], [-50, 2.5, 0] ]; for (let i = 0; i < 4; i++) { const wall = new THREE.Mesh(wallGeometries[i], wallMaterial); wall.position.set(...wallPositions[i]); wall.castShadow = true; wall.receiveShadow = true; scene.add(wall); walls.push(wall); } // Create some obstacles for (let i = 0; i < 15; i++) { const size = 1 + Math.random() * 3; const height = 1 + Math.random() * 3; const obstacleGeometry = new THREE.BoxGeometry(size, height, size); const obstacle = new THREE.Mesh(obstacleGeometry, wallMaterial); obstacle.position.set( Math.random() * 80 - 40, height / 2, Math.random() * 80 - 40 ); obstacle.castShadow = true; obstacle.receiveShadow = true; scene.add(obstacle); walls.push(obstacle); } return walls; } function createLighting(scene) { // Ambient light const ambientLight = new THREE.AmbientLight(0x404040, 0.5); scene.add(ambientLight); // Directional light (sun) const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8); directionalLight.position.set(10, 20, 10); directionalLight.castShadow = true; // Configure shadow properties directionalLight.shadow.mapSize.width = 2048; directionalLight.shadow.mapSize.height = 2048; directionalLight.shadow.camera.near = 0.5; directionalLight.shadow.camera.far = 50; directionalLight.shadow.camera.left = -30; directionalLight.shadow.camera.right = 30; directionalLight.shadow.camera.top = 30; directionalLight.shadow.camera.bottom = -30; scene.add(directionalLight); // Add some point lights for atmosphere const colors = [0xe9d985, 0xc24d2c, 0x3f4e63]; for (let i = 0; i < 5; i++) { const pointLight = new THREE.PointLight( colors[Math.floor(Math.random() * colors.length)], 0.5, 10 ); pointLight.position.set( Math.random() * 60 - 30, 1 + Math.random() * 3, Math.random() * 60 - 30 ); pointLight.castShadow = true; scene.add(pointLight); } }