Spaces:
Running
Running
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Three.js 3D Combat Game - Auto Features</title> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script> | |
<script src="https://cdn.tailwindcss.com"></script> | |
<style> | |
body { | |
margin: 0; | |
overflow: hidden; | |
font-family: 'Inter', sans-serif; | |
background-color: #1a202c; | |
color: #e2e8f0; | |
display: flex; | |
flex-direction: column; | |
align-items: center; | |
justify-content: center; | |
height: 100vh; | |
position: relative; | |
} | |
#game-canvas-wrapper { | |
width: 100vw; | |
height: 100vh; | |
border: none; | |
border-radius: 0; | |
position: relative; | |
} | |
canvas { | |
display: block; | |
width: 100%; | |
height: 100%; | |
} | |
/* Score and Shield Status UI (Sides) */ | |
.player-side-ui { | |
position: absolute; | |
top: 20px; | |
padding: 10px 15px; | |
font-size: 1.1rem; | |
font-weight: bold; | |
color: #1a202c; | |
border-radius: 0.375rem; | |
box-shadow: 0 2px 4px rgba(0,0,0,0.2); | |
z-index: 10; | |
background-color: rgba(255,255,255,0.1); /* Fallback */ | |
} | |
#player1-side-ui { | |
left: 20px; | |
background-color: #38b2ac; /* Teal */ | |
} | |
#player2-side-ui { | |
right: 20px; | |
background-color: #ed8936; /* Orange */ | |
} | |
.shield-timer { | |
font-size: 0.9rem; | |
margin-top: 5px; | |
font-weight: normal; | |
} | |
/* Health Bars Container (Top Center) */ | |
#health-bars-container { | |
position: absolute; | |
top: 15px; | |
left: 50%; | |
transform: translateX(-50%); | |
display: flex; | |
gap: 20px; /* Space between health bars */ | |
z-index: 11; /* Above side UIs */ | |
align-items: center; | |
} | |
.health-bar-wrapper { | |
display: flex; | |
flex-direction: column; | |
align-items: center; | |
} | |
.health-bar-label { | |
font-size: 0.9rem; | |
font-weight: bold; | |
margin-bottom: 3px; | |
} | |
.health-bar { | |
width: 200px; /* Width of the health bar */ | |
height: 20px; /* Height of the health bar */ | |
background-color: #4a5568; /* Tailwind gray-600 (darker background) */ | |
border-radius: 5px; | |
border: 2px solid #718096; /* Tailwind gray-500 (border) */ | |
overflow: hidden; /* To contain the fill */ | |
box-shadow: inset 0 1px 3px rgba(0,0,0,0.2); | |
} | |
.health-bar-fill { | |
height: 100%; | |
width: 100%; /* Start full */ | |
border-radius: 3px; /* Slightly smaller radius for fill */ | |
transition: width 0.3s ease-out, background-color 0.3s ease; | |
} | |
#player1-health-bar-fill { background-color: #38b2ac; } /* Teal */ | |
#player2-health-bar-fill { background-color: #ed8936; } /* Orange */ | |
.controls-and-reset { | |
position: absolute; | |
bottom: 10px; | |
left: 50%; | |
transform: translateX(-50%); | |
display: flex; | |
flex-direction: column; | |
align-items: center; | |
width: 100%; | |
max-width: 700px; | |
z-index: 10; | |
} | |
.instructions { | |
background-color: rgba(45, 55, 72, 0.9); | |
padding: 0.75rem 1.25rem; | |
border-radius: 0.5rem; | |
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); | |
text-align: center; | |
margin-bottom: 10px; | |
} | |
.instructions h1 { font-size: 1.2rem; margin-bottom: 0.3rem; } | |
.instructions p { font-size: 0.85rem; margin-bottom: 0.2rem; } | |
kbd { | |
display: inline-block; | |
padding: 0.25rem 0.5rem; | |
font-size: 0.75rem; | |
font-weight: 600; | |
color: #1f2937; | |
background-color: #f3f4f6; | |
border: 1px solid #d1d5db; | |
border-radius: 0.25rem; | |
margin: 0 0.1rem; | |
} | |
#reset-button { | |
padding: 0.7rem 1.5rem; | |
font-size: 1rem; | |
font-weight: bold; | |
color: white; | |
background-color: #c53030; | |
border: none; | |
border-radius: 0.375rem; | |
cursor: pointer; | |
transition: background-color 0.2s; | |
} | |
#reset-button:hover { | |
background-color: #9b2c2c; | |
} | |
#game-over-message { | |
position: absolute; | |
top: 50%; | |
left: 50%; | |
transform: translate(-50%, -50%); | |
background-color: rgba(0, 0, 0, 0.9); | |
color: white; | |
padding: 25px 35px; | |
border-radius: 10px; | |
font-size: 2rem; | |
text-align: center; | |
z-index: 20; | |
display: none; | |
border: 3px solid #e53e3e; | |
} | |
</style> | |
</head> | |
<body> | |
<div id="player1-side-ui" class="player-side-ui"> | |
<div>P1 Score: <span id="player1-score-text">0</span></div> | |
<div class="shield-timer">Shield: <span id="player1-shield-status">READY</span></div> | |
</div> | |
<div id="player2-side-ui" class="player-side-ui"> | |
<div>P2 Score: <span id="player2-score-text">0</span></div> | |
<div class="shield-timer">Shield: <span id="player2-shield-status">READY</span></div> | |
</div> | |
<div id="health-bars-container"> | |
<div class="health-bar-wrapper"> | |
<div class="health-bar-label" style="color: #38b2ac;">Player 1 Health</div> | |
<div id="player1-health-bar" class="health-bar"> | |
<div id="player1-health-bar-fill" class="health-bar-fill"></div> | |
</div> | |
</div> | |
<div class="health-bar-wrapper"> | |
<div class="health-bar-label" style="color: #ed8936;">Player 2 Health</div> | |
<div id="player2-health-bar" class="health-bar"> | |
<div id="player2-health-bar-fill" class="health-bar-fill"></div> | |
</div> | |
</div> | |
</div> | |
<div id="game-canvas-wrapper"> | |
<div id="game-over-message">Game Over!</div> | |
</div> | |
<div class="controls-and-reset"> | |
<div class="instructions"> | |
<h1>3D Auto Combat!</h1> | |
<p>P1 (Teal): <kbd>W</kbd><kbd>S</kbd> Fwd/Back | <kbd>A</kbd><kbd>D</kbd> Turn</p> | |
<p>P2 (Orange): <kbd>I</kbd><kbd>K</kbd> Fwd/Back | <kbd>J</kbd><kbd>L</kbd> Turn</p> | |
<p><kbd>SPACEBAR</kbd> to Heal Both Players</p> | |
</div> | |
<button id="reset-button">Reset Game</button> | |
</div> | |
<script> | |
// --- Game Constants --- | |
const PLAYER_SPEED = 0.15; | |
const PLAYER_RADIUS = 0.5; | |
const PROJECTILE_SIZE = 0.15; | |
const PROJECTILE_SPEED = 0.4; | |
const PLAYER_MAX_HEALTH = 10; // Increased max health for longer gameplay | |
const INVADER_RADIUS = 0.6; | |
const PARATROOPER_RADIUS = 0.4; | |
const INVADER_FIRE_COOLDOWN = 1800; | |
const PARATROOPER_FIRE_COOLDOWN = 2200; | |
const PLAYER_AUTO_FIRE_COOLDOWN = 400; // Auto-fire rate | |
const SHIELD_DURATION = 7000; // 7 seconds | |
const SHIELD_COOLDOWN = 15000; // 15 seconds | |
const AUTO_SHIELD_HEALTH_THRESHOLD = 3; // Activate shield if health <= this | |
const AUTO_SHIELD_CONSIDER_INTERVAL = 3000; // ms, how often to consider auto-shield if not critical | |
const GAME_PLANE_WIDTH = 30; // Increased for full screen feel | |
const GAME_PLANE_HEIGHT = 20; // Increased for full screen feel | |
const DIVIDING_LINE_POS_X = 0; | |
const PARATROOPER_SPAWN_Y = 15; // Spawn higher | |
const PARATROOPER_DROP_SPEED = 0.05; | |
const PARATROOPER_SPAWN_INTERVAL = 4500; | |
// --- Global Variables --- | |
let scene, camera, renderer; | |
let player1, player2; | |
let projectiles = []; | |
let invaders = []; | |
let paratroopers = []; | |
let keysPressed = {}; | |
let gameOver = false; | |
let lastParatrooperSpawnTime = 0; | |
let ambientLight, directionalLight; | |
let groundPlane, dividingLineMesh; | |
// DOM Elements | |
let player1ScoreEl, player1ShieldStatusEl, player1HealthBarFillEl; | |
let player2ScoreEl, player2ShieldStatusEl, player2HealthBarFillEl; | |
let resetButtonEl, gameOverMessageEl, gameCanvasWrapperEl; | |
// --- Initialization --- | |
function init() { | |
gameCanvasWrapperEl = document.getElementById('game-canvas-wrapper'); | |
player1ScoreEl = document.getElementById('player1-score-text'); | |
player1ShieldStatusEl = document.getElementById('player1-shield-status'); | |
player1HealthBarFillEl = document.getElementById('player1-health-bar-fill'); | |
player2ScoreEl = document.getElementById('player2-score-text'); | |
player2ShieldStatusEl = document.getElementById('player2-shield-status'); | |
player2HealthBarFillEl = document.getElementById('player2-health-bar-fill'); | |
resetButtonEl = document.getElementById('reset-button'); | |
gameOverMessageEl = document.getElementById('game-over-message'); | |
scene = new THREE.Scene(); | |
scene.background = new THREE.Color(0x1a202c); | |
setupCamera(); | |
setupLights(); | |
renderer = new THREE.WebGLRenderer({ antialias: true }); | |
renderer.setSize(window.innerWidth, window.innerHeight); | |
renderer.shadowMap.enabled = true; | |
gameCanvasWrapperEl.appendChild(renderer.domElement); | |
createGround(); | |
createDividingLine(); | |
resetButtonEl.addEventListener('click', resetGame); | |
document.addEventListener('keydown', onKeyDown); | |
document.addEventListener('keyup', onKeyUp); | |
window.addEventListener('resize', onWindowResize, false); | |
resetGame(); | |
animate(); | |
} | |
function setupCamera() { | |
const aspect = window.innerWidth / window.innerHeight; | |
camera = new THREE.PerspectiveCamera(60, aspect, 0.1, 1000); // Wider FOV | |
camera.position.set(0, GAME_PLANE_WIDTH * 0.9, GAME_PLANE_HEIGHT * 0.7); // Adjusted for larger plane | |
camera.lookAt(0, 0, 0); | |
} | |
function setupLights() { | |
ambientLight = new THREE.AmbientLight(0xffffff, 0.7); | |
scene.add(ambientLight); | |
directionalLight = new THREE.DirectionalLight(0xffffff, 0.9); | |
directionalLight.position.set(GAME_PLANE_WIDTH * 0.5, 30, GAME_PLANE_HEIGHT * 0.5); // Higher, more spread | |
directionalLight.castShadow = true; | |
directionalLight.shadow.mapSize.width = 2048; // Better shadow quality | |
directionalLight.shadow.mapSize.height = 2048; | |
directionalLight.shadow.camera.near = 0.5; | |
directionalLight.shadow.camera.far = 80; | |
directionalLight.shadow.camera.left = -GAME_PLANE_WIDTH; | |
directionalLight.shadow.camera.right = GAME_PLANE_WIDTH; | |
directionalLight.shadow.camera.top = GAME_PLANE_HEIGHT; | |
directionalLight.shadow.camera.bottom = -GAME_PLANE_HEIGHT; | |
scene.add(directionalLight); | |
} | |
function createGround() { | |
const groundGeometry = new THREE.PlaneGeometry(GAME_PLANE_WIDTH, GAME_PLANE_HEIGHT); | |
const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x2d3748, side: THREE.DoubleSide }); // Darker gray | |
groundPlane = new THREE.Mesh(groundGeometry, groundMaterial); | |
groundPlane.rotation.x = -Math.PI / 2; | |
groundPlane.receiveShadow = true; | |
scene.add(groundPlane); | |
} | |
function createDividingLine() { | |
const lineMaterial = new THREE.LineBasicMaterial({ color: 0x6b7280, linewidth: 3 }); // Tailwind gray-500, thicker | |
const points = []; | |
points.push(new THREE.Vector3(DIVIDING_LINE_POS_X, 0.02, -GAME_PLANE_HEIGHT / 2)); // Slightly above ground | |
points.push(new THREE.Vector3(DIVIDING_LINE_POS_X, 0.02, GAME_PLANE_HEIGHT / 2)); | |
const lineGeometry = new THREE.BufferGeometry().setFromPoints(points); | |
dividingLineMesh = new THREE.Line(lineGeometry, lineMaterial); | |
scene.add(dividingLineMesh); | |
} | |
function resetGame() { | |
gameOver = false; | |
gameOverMessageEl.style.display = 'none'; | |
keysPressed = {}; | |
projectiles.forEach(p => scene.remove(p)); projectiles = []; | |
invaders.forEach(i => scene.remove(i.meshGroup)); invaders = []; | |
paratroopers.forEach(pt => scene.remove(pt.meshGroup)); paratroopers = []; | |
if (player1) scene.remove(player1.meshGroup); | |
if (player2) scene.remove(player2.meshGroup); | |
createPlayers(); | |
createInitialInvaders(); | |
lastParatrooperSpawnTime = Date.now(); | |
updateUI(); // Initial UI update including health bars | |
} | |
function createPlayerModel(color) { | |
const group = new THREE.Group(); | |
const bodyRadius = PLAYER_RADIUS * 0.6; | |
const bodyHeight = PLAYER_RADIUS * 1.2; | |
const bodyCylinderGeom = new THREE.CylinderGeometry(bodyRadius, bodyRadius, bodyHeight, 16); | |
const bodyMaterial = new THREE.MeshStandardMaterial({ color: color, metalness: 0.3, roughness: 0.6 }); | |
const bodyCylinder = new THREE.Mesh(bodyCylinderGeom, bodyMaterial); | |
bodyCylinder.castShadow = true; | |
bodyCylinder.name = "body"; // For hit flash targeting | |
group.add(bodyCylinder); | |
const sphereGeom = new THREE.SphereGeometry(bodyRadius, 16, 8); | |
const topSphere = new THREE.Mesh(sphereGeom, bodyMaterial); | |
topSphere.position.y = bodyHeight / 2; | |
topSphere.castShadow = true; | |
group.add(topSphere); | |
const bottomSphere = new THREE.Mesh(sphereGeom, bodyMaterial); | |
bottomSphere.position.y = -bodyHeight / 2; | |
bottomSphere.castShadow = true; | |
group.add(bottomSphere); | |
const barrelLength = PLAYER_RADIUS * 0.8; | |
const barrelRadius = PLAYER_RADIUS * 0.15; | |
const barrelGeom = new THREE.CylinderGeometry(barrelRadius, barrelRadius, barrelLength, 8); | |
const barrelMaterial = new THREE.MeshStandardMaterial({ color: 0x666666, metalness: 0.5, roughness: 0.4 }); | |
const barrel = new THREE.Mesh(barrelGeom, barrelMaterial); | |
barrel.rotation.z = Math.PI / 2; | |
barrel.position.x = bodyRadius + barrelLength / 2 - 0.1; | |
barrel.position.y = 0; | |
barrel.castShadow = true; | |
group.add(barrel); | |
group.position.y = bodyHeight/2; | |
return group; | |
} | |
function createInvaderModel(color) { | |
const group = new THREE.Group(); | |
const mainBodySize = INVADER_RADIUS * 0.8; | |
const bodyGeom = new THREE.BoxGeometry(mainBodySize, mainBodySize, mainBodySize); | |
const bodyMaterial = new THREE.MeshStandardMaterial({ color: color, metalness: 0.2, roughness: 0.7 }); | |
const body = new THREE.Mesh(bodyGeom, bodyMaterial); | |
body.castShadow = true; | |
body.name = "body"; | |
group.add(body); | |
const eyeRadius = mainBodySize * 0.15; | |
const eyeGeom = new THREE.SphereGeometry(eyeRadius, 8, 8); | |
const eyeMaterial = new THREE.MeshStandardMaterial({ color: 0xffff00, emissive: 0xffff00, emissiveIntensity: 0.5 }); | |
const eye1 = new THREE.Mesh(eyeGeom, eyeMaterial); | |
eye1.position.set(mainBodySize * 0.25, mainBodySize * 0.2, mainBodySize * 0.51); | |
group.add(eye1); | |
const eye2 = new THREE.Mesh(eyeGeom, eyeMaterial); | |
eye2.position.set(-mainBodySize * 0.25, mainBodySize * 0.2, mainBodySize * 0.51); | |
group.add(eye2); | |
group.position.y = mainBodySize / 2; | |
return group; | |
} | |
function createParatrooperModel(color) { | |
const group = new THREE.Group(); | |
const bodyRadius = PARATROOPER_RADIUS * 0.7; | |
const bodyHeight = PARATROOPER_RADIUS * 1.5; | |
const bodyGeom = new THREE.CylinderGeometry(bodyRadius*0.7, bodyRadius, bodyHeight, 12); | |
const bodyMaterial = new THREE.MeshStandardMaterial({ color: color, metalness: 0.3, roughness: 0.6 }); | |
const body = new THREE.Mesh(bodyGeom, bodyMaterial); | |
body.castShadow = true; | |
body.name = "body"; | |
group.add(body); | |
const canopyRadius = PARATROOPER_RADIUS * 1.5; | |
const canopyGeom = new THREE.SphereGeometry(canopyRadius, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2); | |
const canopyMaterial = new THREE.MeshStandardMaterial({ color: 0xf0f0f0, transparent: true, opacity: 0.75, side: THREE.DoubleSide }); | |
const canopy = new THREE.Mesh(canopyGeom, canopyMaterial); | |
canopy.position.y = bodyHeight / 2 + canopyRadius * 0.3; | |
canopy.castShadow = false; | |
group.add(canopy); | |
return group; | |
} | |
function createPlayers() { | |
player1 = { meshGroup: createPlayerModel(0x38b2ac), | |
health: PLAYER_MAX_HEALTH, score: 0, lastShotTime: 0, | |
shieldActive: false, shieldEndTime: 0, shieldCooldownEndTime: 0, | |
lastAutoShieldConsiderTime: 0, | |
id: 'player1', radius: PLAYER_RADIUS | |
}; | |
player1.meshGroup.position.set(-GAME_PLANE_WIDTH / 4, player1.meshGroup.position.y, 0); | |
scene.add(player1.meshGroup); | |
player2 = { meshGroup: createPlayerModel(0xed8936), | |
health: PLAYER_MAX_HEALTH, score: 0, lastShotTime: 0, | |
shieldActive: false, shieldEndTime: 0, shieldCooldownEndTime: 0, | |
lastAutoShieldConsiderTime: 0, | |
id: 'player2', radius: PLAYER_RADIUS | |
}; | |
player2.meshGroup.position.set(GAME_PLANE_WIDTH / 4, player2.meshGroup.position.y, 0); | |
player2.meshGroup.rotation.y = Math.PI; | |
scene.add(player2.meshGroup); | |
} | |
function createInitialInvaders() { | |
const invaderPositions = [ | |
new THREE.Vector3(-GAME_PLANE_WIDTH / 3, 0, GAME_PLANE_HEIGHT / 3.5), | |
new THREE.Vector3(GAME_PLANE_WIDTH / 3, 0, -GAME_PLANE_HEIGHT / 3.5), | |
new THREE.Vector3(-GAME_PLANE_WIDTH / 3.5, 0, -GAME_PLANE_HEIGHT / 4), | |
new THREE.Vector3(GAME_PLANE_WIDTH / 3.5, 0, GAME_PLANE_HEIGHT / 4), | |
]; | |
invaderPositions.forEach((pos, index) => { | |
const invaderMeshGroup = createInvaderModel(0x9f7aea); | |
invaderMeshGroup.position.set(pos.x, invaderMeshGroup.position.y, pos.z); | |
if (pos.x < 0) invaderMeshGroup.rotation.y = Math.PI / 2; | |
else invaderMeshGroup.rotation.y = -Math.PI / 2; | |
const invader = { | |
meshGroup: invaderMeshGroup, health: 1, id: `invader${index}`, | |
lastShotTime: 0, radius: INVADER_RADIUS, originalZ: pos.z, oscillationTime: Math.random() * Math.PI * 2 | |
}; | |
scene.add(invader.meshGroup); | |
invaders.push(invader); | |
}); | |
} | |
function spawnParatrooper() { | |
const spawnX = (Math.random() - 0.5) * (GAME_PLANE_WIDTH * 0.95); | |
const spawnZ = (Math.random() - 0.5) * (GAME_PLANE_HEIGHT * 0.95); | |
const paratrooperMeshGroup = createParatrooperModel(0xdd6b20); | |
paratrooperMeshGroup.position.set(spawnX, PARATROOPER_SPAWN_Y, spawnZ); | |
const bodyHeight = PARATROOPER_RADIUS * 1.5; | |
const paratrooper = { | |
meshGroup: paratrooperMeshGroup, health: 1, id: `paratrooper${paratroopers.length}`, | |
lastShotTime: 0, radius: PARATROOPER_RADIUS, | |
targetY: bodyHeight / 2, landed: false | |
}; | |
scene.add(paratrooper.meshGroup); | |
paratroopers.push(paratrooper); | |
lastParatrooperSpawnTime = Date.now(); | |
} | |
function createProjectile(shooter) { | |
if (!shooter || shooter.health <= 0) return; | |
// Auto-fire cooldown is handled by handleAutoShooting, so direct call implies readiness | |
// However, for enemies, we still need the cooldown check here if they are not part of handleAutoShooting | |
if (shooter.id.includes('invader') || shooter.id.includes('paratrooper')) { | |
const now = Date.now(); | |
const fireCooldown = shooter.id.includes('invader') ? INVADER_FIRE_COOLDOWN : PARATROOPER_FIRE_COOLDOWN; | |
if (now - shooter.lastShotTime < fireCooldown) return; | |
shooter.lastShotTime = now; | |
} | |
const projectileGeom = new THREE.SphereGeometry(PROJECTILE_SIZE, 8, 8); | |
let projectileColor; | |
let velocity = new THREE.Vector3(); | |
const startPos = shooter.meshGroup.position.clone(); | |
if(shooter.id.includes('player')) startPos.y += PLAYER_RADIUS * 0.8; | |
else startPos.y += INVADER_RADIUS * 0.4; | |
const localForward = new THREE.Vector3(1, 0, 0); | |
const worldForward = localForward.clone().applyQuaternion(shooter.meshGroup.quaternion); | |
if (shooter.id.includes('player')) { | |
projectileColor = shooter.id === 'player1' ? 0x81e6d9 : 0xfbd38d; | |
velocity.copy(worldForward).multiplyScalar(PROJECTILE_SPEED); | |
} else if (shooter.id.includes('invader') || shooter.id.includes('paratrooper')) { | |
projectileColor = shooter.id.includes('invader') ? 0xc4b5fd : 0xffa07a; | |
const targetPlayer = (player1.health > 0 && player2.health > 0) ? (Math.random() < 0.5 ? player1 : player2) : (player1.health > 0 ? player1 : (player2.health > 0 ? player2 : null)); | |
if (targetPlayer) { | |
velocity.subVectors(targetPlayer.meshGroup.position, shooter.meshGroup.position).normalize().multiplyScalar(PROJECTILE_SPEED * 0.8); | |
} else { return; } | |
} else { return; } | |
const projectileMaterial = new THREE.MeshStandardMaterial({ color: projectileColor, emissive: projectileColor, emissiveIntensity: 0.7 }); | |
const projectile = new THREE.Mesh(projectileGeom, projectileMaterial); | |
projectile.castShadow = true; | |
const offset = worldForward.clone().multiplyScalar(shooter.radius * 1.1); | |
startPos.add(offset); | |
projectile.position.copy(startPos); | |
projectile.userData = { ownerId: shooter.id, velocity: velocity, creationTime: Date.now() }; | |
scene.add(projectile); | |
projectiles.push(projectile); | |
} | |
// --- Event Handlers --- | |
function onKeyDown(event) { | |
if (gameOver && event.key.toLowerCase() !== " ") return; | |
keysPressed[event.key.toLowerCase()] = true; | |
const key = event.key.toLowerCase(); | |
if (key === ' ') { // Spacebar Heal | |
if (player1) player1.health = PLAYER_MAX_HEALTH; | |
if (player2) player2.health = PLAYER_MAX_HEALTH; | |
if (gameOver) { | |
gameOver = false; | |
gameOverMessageEl.style.display = 'none'; | |
// Optionally, could call resetGame() for a full reset, or just continue | |
} | |
updateUI(); | |
event.preventDefault(); | |
} | |
// Manual fire and shield keys are removed for auto-features | |
} | |
function onKeyUp(event) { | |
keysPressed[event.key.toLowerCase()] = false; | |
} | |
function onWindowResize() { | |
renderer.setSize(window.innerWidth, window.innerHeight); | |
camera.aspect = window.innerWidth / window.innerHeight; | |
camera.updateProjectionMatrix(); | |
} | |
function activateShield(player) { // Now called by auto-shield logic | |
const now = Date.now(); | |
if (player && !player.shieldActive && now > player.shieldCooldownEndTime) { | |
player.shieldActive = true; | |
player.shieldEndTime = now + SHIELD_DURATION; | |
player.shieldCooldownEndTime = player.shieldEndTime + SHIELD_COOLDOWN; | |
if (!player.shieldMesh) { | |
const shieldGeom = new THREE.SphereGeometry(player.radius * 1.6, 16, 16); // Slightly larger shield | |
const shieldMat = new THREE.MeshStandardMaterial({ color: 0x00ddff, transparent: true, opacity: 0.30, emissive: 0x00ccee, emissiveIntensity: 0.25 }); | |
player.shieldMesh = new THREE.Mesh(shieldGeom, shieldMat); | |
player.meshGroup.add(player.shieldMesh); | |
} | |
player.shieldMesh.visible = true; | |
updateUI(); | |
} | |
} | |
function updateShields() { // Checks for shield expiration | |
const now = Date.now(); | |
[player1, player2].forEach(player => { | |
if (player && player.shieldActive && now > player.shieldEndTime) { | |
player.shieldActive = false; | |
if (player.shieldMesh) player.shieldMesh.visible = false; | |
updateUI(); | |
} | |
}); | |
} | |
function handleAutoShooting() { | |
const now = Date.now(); | |
[player1, player2].forEach(player => { | |
if (player && player.health > 0 && !player.shieldActive) { // Don't shoot if shielded | |
if (now - player.lastShotTime > PLAYER_AUTO_FIRE_COOLDOWN) { | |
createProjectile(player); | |
player.lastShotTime = now; // Update lastShotTime here after successful fire | |
} | |
} | |
}); | |
} | |
function handleAutoShielding() { | |
const now = Date.now(); | |
[player1, player2].forEach(player => { | |
if (player && player.health > 0 && !player.shieldActive && now > player.shieldCooldownEndTime) { | |
// Critical health trigger | |
if (player.health <= AUTO_SHIELD_HEALTH_THRESHOLD) { | |
activateShield(player); | |
player.lastAutoShieldConsiderTime = now; // Reset consider timer | |
return; // Shield activated | |
} | |
// Periodic consideration if not full health | |
if (player.health < PLAYER_MAX_HEALTH && (now - player.lastAutoShieldConsiderTime > AUTO_SHIELD_CONSIDER_INTERVAL)) { | |
if (Math.random() < 0.3) { // 30% chance to auto-shield if conditions met | |
activateShield(player); | |
} | |
player.lastAutoShieldConsiderTime = now; | |
} | |
} | |
}); | |
} | |
function handlePlayerMovement(player, forwardKey, backwardKey, turnLeftKey, turnRightKey) { | |
if (!player || player.health <= 0) return; | |
let speed = 0; | |
if (keysPressed[forwardKey]) speed = PLAYER_SPEED; | |
if (keysPressed[backwardKey]) speed = -PLAYER_SPEED * 0.7; | |
if (keysPressed[turnLeftKey]) player.meshGroup.rotation.y += 0.05; | |
if (keysPressed[turnRightKey]) player.meshGroup.rotation.y -= 0.05; | |
if (speed !== 0) { | |
const moveDirection = new THREE.Vector3(1, 0, 0); | |
moveDirection.applyQuaternion(player.meshGroup.quaternion); | |
player.meshGroup.position.add(moveDirection.multiplyScalar(speed)); | |
} | |
const halfWorldWidth = GAME_PLANE_WIDTH / 2 - player.radius; | |
const halfWorldDepth = GAME_PLANE_HEIGHT / 2 - player.radius; | |
player.meshGroup.position.z = Math.max(-halfWorldDepth, Math.min(halfWorldDepth, player.meshGroup.position.z)); | |
if (player.id === 'player1') { | |
player.meshGroup.position.x = Math.max(-halfWorldWidth, Math.min(DIVIDING_LINE_POS_X - player.radius, player.meshGroup.position.x)); | |
} else { | |
player.meshGroup.position.x = Math.max(DIVIDING_LINE_POS_X + player.radius, Math.min(halfWorldWidth, player.meshGroup.position.x)); | |
} | |
const otherPlayer = player.id === 'player1' ? player2 : player1; | |
if (otherPlayer && otherPlayer.health > 0) { | |
const distSq = player.meshGroup.position.distanceToSquared(otherPlayer.meshGroup.position); | |
if (distSq < (player.radius + otherPlayer.radius) ** 2) { | |
const delta = player.meshGroup.position.clone().sub(otherPlayer.meshGroup.position).normalize(); | |
const overlap = (player.radius + otherPlayer.radius) - Math.sqrt(distSq); | |
player.meshGroup.position.add(delta.multiplyScalar(overlap / 2 + 0.01)); | |
} | |
} | |
} | |
function updateInvaderBehavior() { | |
invaders.forEach(invader => { | |
if (invader.health <= 0) return; | |
invader.oscillationTime += 0.025; | |
let targetZ = invader.originalZ + Math.sin(invader.oscillationTime) * (GAME_PLANE_HEIGHT * 0.15); | |
invader.meshGroup.position.z = THREE.MathUtils.lerp(invader.meshGroup.position.z, targetZ, 0.1); | |
if (Date.now() - invader.lastShotTime > INVADER_FIRE_COOLDOWN) { // Enemies still use their own fire logic | |
if (Math.random() < 0.4) createProjectile(invader); | |
} | |
}); | |
} | |
function updateParatroopers() { | |
for (let i = paratroopers.length - 1; i >= 0; i--) { | |
const pt = paratroopers[i]; | |
if (pt.health <= 0) continue; | |
if (pt.meshGroup.position.y > pt.targetY) { | |
pt.meshGroup.position.y -= PARATROOPER_DROP_SPEED; | |
} else { | |
pt.meshGroup.position.y = pt.targetY; | |
if(!pt.landed) { | |
const targetPlayer = (player1.health > 0 && player2.health > 0) ? (Math.random() < 0.5 ? player1 : player2) : (player1.health > 0 ? player1 : (player2.health > 0 ? player2 : null)); | |
if(targetPlayer) { | |
// Make paratrooper look at target on XZ plane | |
const targetPosXZ = new THREE.Vector3(targetPlayer.meshGroup.position.x, pt.meshGroup.position.y, targetPlayer.meshGroup.position.z); | |
pt.meshGroup.lookAt(targetPosXZ); | |
} | |
pt.landed = true; | |
} | |
} | |
if (Date.now() - pt.lastShotTime > PARATROOPER_FIRE_COOLDOWN) { // Enemies still use their own fire logic | |
if (Math.random() < 0.35) createProjectile(pt); | |
} | |
} | |
if (Date.now() - lastParatrooperSpawnTime > PARATROOPER_SPAWN_INTERVAL && paratroopers.length < 8) { // Max 8 paratroopers | |
spawnParatrooper(); | |
} | |
} | |
function updateProjectiles() { | |
for (let i = projectiles.length - 1; i >= 0; i--) { | |
const p = projectiles[i]; | |
p.position.add(p.userData.velocity); | |
if (Date.now() - p.userData.creationTime > 4000 || | |
Math.abs(p.position.x) > GAME_PLANE_WIDTH / 2 + 5 || | |
Math.abs(p.position.z) > GAME_PLANE_HEIGHT / 2 + 5 || | |
p.position.y < -2 || p.position.y > PARATROOPER_SPAWN_Y + 5) { | |
scene.remove(p); | |
projectiles.splice(i, 1); | |
continue; | |
} | |
checkProjectileHit(p, i); | |
} | |
} | |
function getHitFlashMaterial(meshGroup) { | |
if (meshGroup && meshGroup.children) { | |
let bodyMesh = meshGroup.children.find(child => child.name === 'body' && child.material && child.material.isMeshStandardMaterial); | |
if (bodyMesh) return bodyMesh.material; | |
// Fallback to first standard material if no 'body' | |
for(let child of meshGroup.children){ | |
if(child.isMesh && child.material && child.material.isMeshStandardMaterial){ | |
return child.material; | |
} | |
} | |
} | |
return null; | |
} | |
function checkProjectileHit(projectile, projectileIndex) { | |
const pPos = projectile.position; | |
const ownerId = projectile.userData.ownerId; | |
[player1, player2].forEach(player => { | |
if (!player || player.health <= 0 || player.id === ownerId || player.shieldActive) return; | |
const distSq = pPos.distanceToSquared(player.meshGroup.position); | |
if (distSq < (player.radius + PROJECTILE_SIZE) ** 2) { | |
player.health--; | |
scene.remove(projectile); projectiles.splice(projectileIndex, 1); | |
if (!ownerId.includes('invader') && !ownerId.includes('paratrooper')) { | |
const shooter = ownerId === 'player1' ? player1 : player2; | |
if(shooter) shooter.score++; | |
} | |
const hitMaterial = getHitFlashMaterial(player.meshGroup); | |
if (hitMaterial) { | |
const originalColor = hitMaterial.color.clone(); | |
const originalEmissive = hitMaterial.emissive.clone(); | |
const originalEmissiveIntensity = hitMaterial.emissiveIntensity; | |
hitMaterial.color.setHex(0xff0000); | |
hitMaterial.emissive.setHex(0xff0000); hitMaterial.emissiveIntensity = 0.8; | |
setTimeout(() => { | |
if(hitMaterial) { | |
hitMaterial.color.copy(originalColor); | |
hitMaterial.emissive.copy(originalEmissive); | |
hitMaterial.emissiveIntensity = originalEmissiveIntensity; | |
} | |
}, 120); | |
} | |
updateUI(); checkWinCondition(); return; | |
} | |
}); | |
if (projectiles.indexOf(projectile) === -1) return; | |
const enemyTypes = [invaders, paratroopers]; | |
for (const enemyList of enemyTypes) { | |
for (let j = enemyList.length - 1; j >= 0; j--) { | |
const enemy = enemyList[j]; | |
if (enemy.health <= 0 || ownerId.includes(enemy.id.replace(/\d/g, ''))) continue; | |
const distSq = pPos.distanceToSquared(enemy.meshGroup.position); | |
if (distSq < (enemy.radius + PROJECTILE_SIZE) ** 2) { | |
enemy.health--; | |
scene.remove(projectile); projectiles.splice(projectileIndex, 1); | |
if (ownerId === 'player1' && player1) player1.score++; | |
else if (ownerId === 'player2' && player2) player2.score++; | |
if (enemy.health <= 0) { | |
scene.remove(enemy.meshGroup); | |
enemyList.splice(j, 1); | |
} else { | |
const hitMaterial = getHitFlashMaterial(enemy.meshGroup); | |
if (hitMaterial) { | |
const originalColor = hitMaterial.color.clone(); | |
const originalEmissive = hitMaterial.emissive.clone(); | |
const originalEmissiveIntensity = hitMaterial.emissiveIntensity; | |
hitMaterial.color.setHex(0xff0000); | |
hitMaterial.emissive.setHex(0xff0000); hitMaterial.emissiveIntensity = 0.8; | |
setTimeout(() => { | |
if(hitMaterial) { | |
hitMaterial.color.copy(originalColor); | |
hitMaterial.emissive.copy(originalEmissive); | |
hitMaterial.emissiveIntensity = originalEmissiveIntensity; | |
} | |
}, 120); | |
} | |
} | |
updateUI(); return; | |
} | |
} | |
if (projectiles.indexOf(projectile) === -1) return; | |
} | |
} | |
function updateUI() { | |
if (player1) { | |
player1ScoreEl.textContent = player1.score; | |
const p1HealthPercent = Math.max(0, (player1.health / PLAYER_MAX_HEALTH) * 100); | |
player1HealthBarFillEl.style.width = `${p1HealthPercent}%`; | |
// Change health bar color based on health | |
if (p1HealthPercent <= 30) player1HealthBarFillEl.style.backgroundColor = '#e53e3e'; // Red | |
else if (p1HealthPercent <= 60) player1HealthBarFillEl.style.backgroundColor = '#dd6b20'; // Orange-ish | |
else player1HealthBarFillEl.style.backgroundColor = '#38b2ac'; // Teal (normal) | |
const now = Date.now(); | |
player1ShieldStatusEl.textContent = player1.shieldActive ? `ON (${Math.ceil((player1.shieldEndTime - now)/1000)}s)` : (now < player1.shieldCooldownEndTime ? `CD (${Math.ceil((player1.shieldCooldownEndTime - now)/1000)}s)`: 'READY'); | |
} | |
if (player2) { | |
player2ScoreEl.textContent = player2.score; | |
const p2HealthPercent = Math.max(0, (player2.health / PLAYER_MAX_HEALTH) * 100); | |
player2HealthBarFillEl.style.width = `${p2HealthPercent}%`; | |
if (p2HealthPercent <= 30) player2HealthBarFillEl.style.backgroundColor = '#e53e3e'; // Red | |
else if (p2HealthPercent <= 60) player2HealthBarFillEl.style.backgroundColor = '#dd6b20'; // Orange-ish (darker orange) | |
else player2HealthBarFillEl.style.backgroundColor = '#ed8936'; // Orange (normal) | |
const now = Date.now(); | |
player2ShieldStatusEl.textContent = player2.shieldActive ? `ON (${Math.ceil((player2.shieldEndTime - now)/1000)}s)` : (now < player2.shieldCooldownEndTime ? `CD (${Math.ceil((player2.shieldCooldownEndTime - now)/1000)}s)`: 'READY'); | |
} | |
} | |
function checkWinCondition() { | |
if (gameOver) return; | |
let winner = null; | |
const p1Exists = !!player1; | |
const p2Exists = !!player2; | |
const p1Health = p1Exists ? player1.health : 1; | |
const p2Health = p2Exists ? player2.health : 1; | |
if (p1Exists && p2Exists && p1Health <= 0 && p2Health <=0) winner = "It's a Draw!"; | |
else if (p1Exists && p1Health <= 0) winner = "Player 2 Wins!"; | |
else if (p2Exists && p2Health <= 0) winner = "Player 1 Wins!"; | |
if (winner) { | |
gameOver = true; | |
gameOverMessageEl.textContent = winner; | |
gameOverMessageEl.style.display = 'block'; | |
} | |
} | |
function animate() { | |
requestAnimationFrame(animate); | |
if (!gameOver) { | |
if (player1) handlePlayerMovement(player1, 'w', 's', 'a', 'd'); | |
if (player2) handlePlayerMovement(player2, 'i', 'k', 'j', 'l'); | |
handleAutoShooting(); | |
handleAutoShielding(); | |
updateInvaderBehavior(); | |
updateParatroopers(); | |
updateShields(); // For expiration | |
} | |
updateProjectiles(); | |
updateUI(); | |
renderer.render(scene, camera); | |
} | |
if (document.readyState === 'loading') { | |
document.addEventListener('DOMContentLoaded', init); | |
} else { | |
init(); | |
} | |
</script> | |
</body> | |
</html> | |