import * as THREE from 'three'; import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'; import { PointerLockControls } from 'three/addons/controls/PointerLockControls.js'; // 게임 상수 const GAME_DURATION = 180; const MAP_SIZE = 1000; const TANK_HEIGHT = 0.5; const ENEMY_GROUND_HEIGHT = 0; const ENEMY_SCALE = 10; const MAX_HEALTH = 1000; const ENEMY_MOVE_SPEED = 0.1; const ENEMY_COUNT_MAX = 3; const PARTICLE_COUNT = 15; const BUILDING_COUNT = 30; const ENEMY_CONFIG = { ATTACK_RANGE: 100, ATTACK_INTERVAL: 2000, BULLET_SPEED: 2 }; // TankPlayer 클래스 class TankPlayer { constructor() { this.body = null; this.turret = null; this.position = new THREE.Vector3(0, 0, 0); this.rotation = new THREE.Euler(0, 0, 0); this.turretRotation = 0; this.moveSpeed = 0.5; this.turnSpeed = 0.03; this.turretGroup = new THREE.Group(); this.health = MAX_HEALTH; this.isLoaded = false; this.ammo = 10; this.lastShootTime = 0; this.shootInterval = 1000; this.bullets = []; } async initialize(scene, loader) { try { const bodyResult = await loader.loadAsync('/models/abramsBody.glb'); this.body = bodyResult.scene; this.body.position.copy(this.position); const turretResult = await loader.loadAsync('/models/abramsTurret.glb'); this.turret = turretResult.scene; this.turretGroup.position.y = 0.2; this.turretGroup.add(this.turret); this.body.add(this.turretGroup); this.body.traverse((child) => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); this.turret.traverse((child) => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); scene.add(this.body); this.isLoaded = true; } catch (error) { console.error('Error loading tank models:', error); this.isLoaded = false; } } shoot(scene) { const currentTime = Date.now(); if (currentTime - this.lastShootTime < this.shootInterval || this.ammo <= 0) { if (this.ammo === 0) { console.log('Out of ammo! Reload required.'); } return null; } const bulletGeometry = new THREE.SphereGeometry(0.2); const bulletMaterial = new THREE.MeshBasicMaterial({ color: 0x00ff00 }); const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial); const bulletOffset = new THREE.Vector3(0, 0.5, 2); bulletOffset.applyQuaternion(this.turretGroup.quaternion); bulletOffset.applyQuaternion(this.body.quaternion); bullet.position.copy(this.body.position).add(bulletOffset); const direction = new THREE.Vector3(0, 0, 1); direction.applyQuaternion(this.turretGroup.quaternion); direction.applyQuaternion(this.body.quaternion); bullet.velocity = direction.multiplyScalar(2); scene.add(bullet); this.bullets.push(bullet); this.ammo--; this.lastShootTime = currentTime; // UI 업데이트 document.getElementById('ammo').textContent = `${this.ammo}/10`; // 연기 및 불꽃 효과 생성 this.createSmokeEffect(scene, bulletOffset); this.createMuzzleFlashEffect(scene, bulletOffset); // 발사 소리 재생 this.playRandomFireSound(); return bullet; } createMuzzleFlashEffect(scene, position) { // 빛 효과 const flashLight = new THREE.PointLight(0xffaa00, 2, 10); flashLight.position.copy(this.body.position.clone().add(position)); scene.add(flashLight); // 불꽃 구체 const flashGeometry = new THREE.SphereGeometry(0.3, 16, 16); const flashMaterial = new THREE.MeshBasicMaterial({ color: 0xffaa00 }); const flashMesh = new THREE.Mesh(flashGeometry, flashMaterial); flashMesh.position.copy(this.body.position.clone().add(position)); scene.add(flashMesh); // 불꽃 효과 업데이트 let lifetime = 10; const updateFlash = () => { if (lifetime <= 0) { scene.remove(flashMesh); scene.remove(flashLight); return; } lifetime--; flashMesh.scale.multiplyScalar(0.9); flashLight.intensity *= 0.9; requestAnimationFrame(updateFlash); }; updateFlash(); } // 연기 효과 생성 메서드 createSmokeEffect(scene, position) { const particleCount = 10; for (let i = 0; i < particleCount; i++) { const smokeGeometry = new THREE.SphereGeometry(0.1, 8, 8); const smokeMaterial = new THREE.MeshBasicMaterial({ color: 0x555555, transparent: true, opacity: 0.5 }); const smoke = new THREE.Mesh(smokeGeometry, smokeMaterial); smoke.position.copy(this.body.position.clone().add(position)); smoke.velocity = new THREE.Vector3( (Math.random() - 0.5) * 0.5, Math.random() * 0.2, (Math.random() - 0.5) * 0.5 ); smoke.lifetime = 50; scene.add(smoke); // 연기 업데이트 로직 const updateSmoke = () => { if (smoke.lifetime <= 0) { scene.remove(smoke); return; } smoke.lifetime--; smoke.position.add(smoke.velocity); smoke.material.opacity -= 0.01; requestAnimationFrame(updateSmoke); }; updateSmoke(); } } // 무작위 발사 소리 재생 메서드 playRandomFireSound() { const sounds = [ "sounds/mbtfire1.ogg", "sounds/mbtfire2.ogg", "sounds/mbtfire3.ogg", "sounds/mbtfire4.ogg", "sounds/mbtfire5.ogg" ]; const randomSound = sounds[Math.floor(Math.random() * sounds.length)]; const audio = new Audio(randomSound); audio.volume = 0.5; // 소리 크기를 50%로 줄임 audio.play(); } update(mouseX, mouseY, scene) { if (!this.body || !this.turretGroup) return; // 포탑 회전 방향 설정 const turretDirection = new THREE.Vector3(mouseX, 0, -mouseY).normalize(); const angle = Math.atan2(turretDirection.x, turretDirection.z); this.turretGroup.rotation.y = angle; // 플레이어 총알 이동 처리 for (let i = this.bullets.length - 1; i >= 0; i--) { const bullet = this.bullets[i]; bullet.position.add(bullet.velocity); if ( Math.abs(bullet.position.x) > MAP_SIZE / 2 || Math.abs(bullet.position.z) > MAP_SIZE / 2 ) { scene.remove(bullet); this.bullets.splice(i, 1); } } } move(direction) { if (!this.body) return; const moveVector = new THREE.Vector3(); moveVector.x = direction.x * this.moveSpeed; moveVector.z = direction.z * this.moveSpeed; this.body.position.add(moveVector); } rotate(angle) { if (!this.body) return; this.body.rotation.y += angle * this.turnSpeed; } getPosition() { return this.body ? this.body.position : new THREE.Vector3(); } takeDamage(damage) { this.health -= damage; return this.health <= 0; } } // Enemy 클래스 class Enemy { constructor(scene, position, type = 'tank') { this.scene = scene; this.position = position; this.mesh = null; this.type = type; this.health = type === 'tank' ? 100 : 200; this.lastAttackTime = 0; this.bullets = []; this.isLoaded = false; this.moveSpeed = type === 'tank' ? ENEMY_MOVE_SPEED : ENEMY_MOVE_SPEED * 0.7; } async initialize(loader) { try { const modelPath = this.type === 'tank' ? '/models/enemy1.glb' : '/models/enemy4.glb'; const result = await loader.loadAsync(modelPath); this.mesh = result.scene; this.mesh.position.copy(this.position); this.mesh.scale.set(ENEMY_SCALE, ENEMY_SCALE, ENEMY_SCALE); this.mesh.traverse((child) => { if (child.isMesh) { child.castShadow = true; child.receiveShadow = true; } }); this.scene.add(this.mesh); this.isLoaded = true; } catch (error) { console.error('Error loading enemy model:', error); this.isLoaded = false; } } update(playerPosition) { if (!this.mesh || !this.isLoaded) return; const direction = new THREE.Vector3() .subVectors(playerPosition, this.mesh.position) .normalize(); this.mesh.lookAt(playerPosition); this.mesh.position.add(direction.multiplyScalar(this.moveSpeed)); for (let i = this.bullets.length - 1; i >= 0; i--) { const bullet = this.bullets[i]; bullet.position.add(bullet.velocity); if (Math.abs(bullet.position.x) > MAP_SIZE || Math.abs(bullet.position.z) > MAP_SIZE) { this.scene.remove(bullet); this.bullets.splice(i, 1); } } } shoot(playerPosition) { const currentTime = Date.now(); const attackInterval = this.type === 'tank' ? ENEMY_CONFIG.ATTACK_INTERVAL : ENEMY_CONFIG.ATTACK_INTERVAL * 1.5; if (currentTime - this.lastAttackTime < attackInterval) return; const bulletGeometry = new THREE.SphereGeometry(this.type === 'tank' ? 0.2 : 0.3); const bulletMaterial = new THREE.MeshBasicMaterial({ color: this.type === 'tank' ? 0xff0000 : 0xff6600 }); const bullet = new THREE.Mesh(bulletGeometry, bulletMaterial); bullet.position.copy(this.mesh.position); const direction = new THREE.Vector3() .subVectors(playerPosition, this.mesh.position) .normalize(); const bulletSpeed = this.type === 'tank' ? ENEMY_CONFIG.BULLET_SPEED : ENEMY_CONFIG.BULLET_SPEED * 0.8; bullet.velocity = direction.multiplyScalar(bulletSpeed); this.scene.add(bullet); this.bullets.push(bullet); this.lastAttackTime = currentTime; } takeDamage(damage) { this.health -= damage; return this.health <= 0; } destroy() { if (this.mesh) { this.scene.remove(this.mesh); this.bullets.forEach(bullet => this.scene.remove(bullet)); this.bullets = []; this.isLoaded = false; } } } // Particle 클래스 class Particle { constructor(scene, position) { const geometry = new THREE.SphereGeometry(0.1); const material = new THREE.MeshBasicMaterial({ color: 0xff0000 }); this.mesh = new THREE.Mesh(geometry, material); this.mesh.position.copy(position); this.velocity = new THREE.Vector3( (Math.random() - 0.5) * 0.3, Math.random() * 0.2, (Math.random() - 0.5) * 0.3 ); this.gravity = -0.01; this.lifetime = 60; this.age = 0; scene.add(this.mesh); } update() { this.velocity.y += this.gravity; this.mesh.position.add(this.velocity); this.age++; return this.age < this.lifetime; } destroy(scene) { scene.remove(this.mesh); } } // Game 클래스 class Game { constructor() { this.scene = new THREE.Scene(); this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); this.renderer = new THREE.WebGLRenderer({ antialias: true }); this.renderer.setSize(window.innerWidth, window.innerHeight); this.renderer.shadowMap.enabled = true; document.getElementById('gameContainer').appendChild(this.renderer.domElement); this.tank = new TankPlayer(); this.enemies = []; this.particles = []; this.buildings = []; this.loader = new GLTFLoader(); this.controls = null; this.gameTime = GAME_DURATION; this.score = 0; this.isGameOver = false; this.isLoading = true; this.previousTankPosition = new THREE.Vector3(); this.lastTime = performance.now(); this.gameTimer = null; this.animationFrameId = null; this.mouse = { x: 0, y: 0 }; this.keys = { forward: false, backward: false, left: false, right: false }; this.setupEventListeners(); this.initialize(); } async initialize() { try { // 안개 효과 제거 this.scene.fog = null; this.scene.background = new THREE.Color(0x87CEEB); // 주변광 설정 - 더 밝게 const ambientLight = new THREE.AmbientLight(0xffffff, 0.6); this.scene.add(ambientLight); // 태양광 설정 const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8); directionalLight.position.set(100, 100, 50); directionalLight.castShadow = true; directionalLight.shadow.mapSize.width = 1024; directionalLight.shadow.mapSize.height = 1024; this.scene.add(directionalLight); // 사막 지형 생성 (헬리콥터 게임 스타일) const groundGeometry = new THREE.PlaneGeometry(MAP_SIZE, MAP_SIZE, 100, 100); const groundMaterial = new THREE.MeshStandardMaterial({ color: 0xD2B48C, roughness: 0.8, metalness: 0.2 }); const ground = new THREE.Mesh(groundGeometry, groundMaterial); ground.rotation.x = -Math.PI / 2; ground.receiveShadow = true; // 지형의 기복 추가 (단순화) const vertices = ground.geometry.attributes.position.array; let seed = Math.random() * 100; for (let i = 0; i < vertices.length; i += 3) { vertices[i + 2] = Math.sin(vertices[i] * 0.01) * Math.cos(vertices[i + 1] * 0.01) * 20; } ground.geometry.attributes.position.needsUpdate = true; ground.geometry.computeVertexNormals(); this.scene.add(ground); // 나머지 초기화 코드 await this.addDesertDecorations(); await this.tank.initialize(this.scene, this.loader); if (!this.tank.isLoaded) { throw new Error('Tank loading failed'); } const tankPosition = this.tank.getPosition(); this.camera.position.set( tankPosition.x, tankPosition.y + 15, tankPosition.z - 30 ); this.camera.lookAt(tankPosition); this.isLoading = false; document.getElementById('loading').style.display = 'none'; this.animate(); this.spawnEnemies(); this.startGameTimer(); } catch (error) { console.error('Game initialization error:', error); this.handleLoadingError(); } } // 사막 장식물 추가 메소드 async addDesertDecorations() { // 바위 생성 const rockGeometries = [ new THREE.DodecahedronGeometry(3), new THREE.DodecahedronGeometry(2), new THREE.DodecahedronGeometry(4) ]; const rockMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513, roughness: 0.9, metalness: 0.1 }); for (let i = 0; i < 100; i++) { const rockGeometry = rockGeometries[Math.floor(Math.random() * rockGeometries.length)]; const rock = new THREE.Mesh(rockGeometry, rockMaterial); rock.position.set( (Math.random() - 0.5) * MAP_SIZE * 0.9, Math.random() * 2, (Math.random() - 0.5) * MAP_SIZE * 0.9 ); rock.rotation.set( Math.random() * Math.PI, Math.random() * Math.PI, Math.random() * Math.PI ); rock.scale.set( 1 + Math.random() * 0.5, 1 + Math.random() * 0.5, 1 + Math.random() * 0.5 ); rock.castShadow = true; rock.receiveShadow = true; this.scene.add(rock); } // 선인장 추가 (간단한 geometry로 표현) const cactusGeometry = new THREE.CylinderGeometry(0.5, 0.7, 4, 8); const cactusMaterial = new THREE.MeshStandardMaterial({ color: 0x2F4F2F, roughness: 0.8 }); for (let i = 0; i < 50; i++) { const cactus = new THREE.Mesh(cactusGeometry, cactusMaterial); cactus.position.set( (Math.random() - 0.5) * MAP_SIZE * 0.8, 2, (Math.random() - 0.5) * MAP_SIZE * 0.8 ); cactus.castShadow = true; cactus.receiveShadow = true; this.scene.add(cactus); } } setupEventListeners() { document.addEventListener('keydown', (event) => { if (this.isLoading || this.isGameOver) return; switch(event.code) { case 'KeyW': this.keys.forward = true; break; case 'KeyS': this.keys.backward = true; break; case 'KeyA': this.keys.left = true; break; case 'KeyD': this.keys.right = true; break; } }); document.addEventListener('keyup', (event) => { if (this.isLoading || this.isGameOver) return; switch(event.code) { case 'KeyW': this.keys.forward = false; break; case 'KeyS': this.keys.backward = false; break; case 'KeyA': this.keys.left = false; break; case 'KeyD': this.keys.right = false; break; } }); document.addEventListener('mousemove', (event) => { if (this.isLoading || this.isGameOver || !document.pointerLockElement) return; // 커서 이동에 따라 값 업데이트 (회전 각도를 제한) this.mouse.x = Math.max(Math.min(this.mouse.x + event.movementX * 0.002, 1), -1); this.mouse.y = Math.max(Math.min(this.mouse.y + event.movementY * 0.002, 1), -1); }); document.addEventListener('click', () => { if (!document.pointerLockElement) { document.body.requestPointerLock(); } else if (!this.isGameOver) { const bullet = this.tank.shoot(this.scene); if (bullet) { // Shooting effects could be added here } } }); document.addEventListener('pointerlockchange', () => { if (!document.pointerLockElement) { this.mouse.x = 0; this.mouse.y = 0; } }); window.addEventListener('resize', () => { this.camera.aspect = window.innerWidth / window.innerHeight; this.camera.updateProjectionMatrix(); this.renderer.setSize(window.innerWidth, window.innerHeight); }); } handleMovement() { if (!this.tank.isLoaded || this.isGameOver) return; const direction = new THREE.Vector3(); if (this.keys.forward) direction.z += 1; if (this.keys.backward) direction.z -= 1; if (this.keys.left) direction.x -= 1; if (this.keys.right) direction.x += 1; if (direction.length() > 0) { direction.normalize(); if (this.keys.left) this.tank.rotate(-1); if (this.keys.right) this.tank.rotate(1); direction.applyEuler(this.tank.body.rotation); this.tank.move(direction); } // 카메라 위치 업데이트 const tankPos = this.tank.getPosition(); const turretRotation = this.tank.turretGroup.rotation.y + this.tank.body.rotation.y; const cameraDistance = 30; const cameraHeight = 15; this.camera.position.set( tankPos.x - Math.sin(turretRotation) * cameraDistance, tankPos.y + cameraHeight, tankPos.z - Math.cos(turretRotation) * cameraDistance ); // 카메라가 항상 포탑의 앞 방향을 바라보게 설정 const lookAtPoint = new THREE.Vector3( tankPos.x + Math.sin(turretRotation) * 10, tankPos.y + 5, tankPos.z + Math.cos(turretRotation) * 10 ); this.camera.lookAt(lookAtPoint); } createBuildings() { const buildingTypes = [ { width: 10, height: 30, depth: 10, color: 0x808080 }, { width: 15, height: 40, depth: 15, color: 0x606060 }, { width: 20, height: 50, depth: 20, color: 0x404040 } ]; for (let i = 0; i < BUILDING_COUNT; i++) { const type = buildingTypes[Math.floor(Math.random() * buildingTypes.length)]; const building = this.createBuilding(type); let position; let attempts = 0; do { position = new THREE.Vector3( (Math.random() - 0.5) * (MAP_SIZE - type.width), type.height / 2, (Math.random() - 0.5) * (MAP_SIZE - type.depth) ); attempts++; } while (this.checkBuildingCollision(position, type) && attempts < 50); if (attempts < 50) { building.position.copy(position); this.buildings.push(building); this.scene.add(building); } } return Promise.resolve(); } createBuilding(type) { const geometry = new THREE.BoxGeometry(type.width, type.height, type.depth); const material = new THREE.MeshPhongMaterial({ color: type.color, emissive: 0x222222, specular: 0x111111, shininess: 30 }); const building = new THREE.Mesh(geometry, material); building.castShadow = true; building.receiveShadow = true; return building; } checkBuildingCollision(position, type) { const margin = 5; const bbox = new THREE.Box3( new THREE.Vector3( position.x - (type.width / 2 + margin), 0, position.z - (type.depth / 2 + margin) ), new THREE.Vector3( position.x + (type.width / 2 + margin), type.height, position.z + (type.depth / 2 + margin) ) ); return this.buildings.some(building => { const buildingBox = new THREE.Box3().setFromObject(building); return bbox.intersectsBox(buildingBox); }); } handleLoadingError() { this.isLoading = false; const loadingElement = document.getElementById('loading'); if (loadingElement) { loadingElement.innerHTML = `