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 (
Click to play. Use WASD to move, mouse to aim, and click to shoot.
Click to resume the game.
Score: {score}
Enemies Killed: {enemiesKilled}
Score: {score}
Enemies Killed: {enemiesKilled}