Okay, this is a fun challenge! We'll create a basic 3D endless shooter in Three.js.
This will be a substantial amount of code, so I'll break it down into key components.
HTML (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Three.js Endless Shooter</title>
<style>
body { margin: 0; overflow: hidden; background-color: #000; color: white; font-family: Arial, sans-serif; }
canvas { display: block; }
#info {
position: absolute;
top: 10px;
left: 10px;
padding: 10px;
background-color: rgba(0,0,0,0.5);
border-radius: 5px;
}
#gameOverScreen {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background-color: rgba(0,0,0,0.8);
border: 2px solid white;
border-radius: 10px;
text-align: center;
display: none; /* Hidden by default */
}
#gameOverScreen h2 { margin-top: 0; }
#restartButton {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
}
</style>
</head>
<body>
<div id="info">
<div>Score: <span id="score">0</span></div>
<div>Player HP: <span id="playerHP">100</span></div>
<div>Gun Level: <span id="gunLevel">1</span></div>
<div>Damage: <span id="gunDamage">10</span></div>
<div>Fire Rate: <span id="fireRate">500</span>ms</div>
<div>Next Upgrade: <span id="nextUpgradeScore">500</span></div>
</div>
<div id="gameOverScreen">
<h2>Game Over!</h2>
<p>Final Score: <span id="finalScore">0</span></p>
<button id="restartButton">Restart Game</button>
</div>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.158.0/build/three.module.js"
}
}
</script>
<script type="module" src="game.js"></script>
</body>
</html>
JavaScript (game.js):
import * as THREE from 'three';
// --- Game Settings ---
const PLAYER_SPEED = 0.1;
const PLAYER_HP_MAX = 100;
const BULLET_SPEED = 0.5;
const ENEMY_BASE_HP = 50;
const ENEMY_SPEED = 0.03;
const ENEMY_SPAWN_INTERVAL_MIN = 1000; // ms
const ENEMY_SPAWN_INTERVAL_MAX = 3000; // ms
const SCORE_PER_KILL = 100;
const UPGRADE_SCORE_INTERVAL = 500; // Score needed for next upgrade
// --- Gun Upgrade Tiers ---
const gunUpgrades = [
{ level: 1, damage: 10, fireRate: 500, color: 0x00ff00, bulletSize: 0.1 }, // Slower fire rate
{ level: 2, damage: 15, fireRate: 400, color: 0x00ffff, bulletSize: 0.12 },
{ level: 3, damage: 20, fireRate: 300, color: 0xff00ff, bulletSize: 0.15 },
{ level: 4, damage: 25, fireRate: 200, color: 0xffff00, bulletSize: 0.18, bulletsPerShot: 2, spreadAngle: 5 }, // Multi-shot
{ level: 5, damage: 30, fireRate: 150, color: 0xffa500, bulletSize: 0.2, bulletsPerShot: 3, spreadAngle: 10 } // Wider multi-shot
];
// --- Global Variables ---
let scene, camera, renderer;
let player, playerHP;
let bullets = [];
let enemies = [];
let score = 0;
let lastEnemySpawnTime = 0;
let nextEnemySpawnInterval = ENEMY_SPAWN_INTERVAL_MIN;
let keys = {}; // To track pressed keys
let lastShotTime = 0;
let currentGunLevel = 0; // Index in gunUpgrades array
let nextUpgradeScore = UPGRADE_SCORE_INTERVAL;
let gameRunning = true;
// --- DOM Elements ---
const scoreDisplay = document.getElementById('score');
const playerHPDisplay = document.getElementById('playerHP');
const gunLevelDisplay = document.getElementById('gunLevel');
const gunDamageDisplay = document.getElementById('gunDamage');
const fireRateDisplay = document.getElementById('fireRate');
const nextUpgradeScoreDisplay = document.getElementById('nextUpgradeScore');
const gameOverScreen = document.getElementById('gameOverScreen');
const finalScoreDisplay = document.getElementById('finalScore');
const restartButton = document.getElementById('restartButton');
// --- Initialization ---
function init() {
// Scene
scene = new THREE.Scene();
// Camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 10, 10); // Elevated view
camera.lookAt(0, 0, 0);
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 10, 7);
scene.add(directionalLight);
// Player
createPlayer();
resetPlayerState();
// Event Listeners
document.addEventListener('keydown', onKeyDown);
document.addEventListener('keyup', onKeyUp);
document.addEventListener('mousedown', onMouseDown); // For shooting
window.addEventListener('resize', onWindowResize);
restartButton.addEventListener('click', restartGame);
// Initial gun setup
applyGunUpgrade();
updateUI();
// Start game loop
animate();
}
function resetPlayerState() {
playerHP = PLAYER_HP_MAX;
score = 0;
currentGunLevel = 0;
nextUpgradeScore = UPGRADE_SCORE_INTERVAL;
applyGunUpgrade(); // Apply base gun stats
// Clear existing entities
bullets.forEach(b => scene.remove(b.mesh));
bullets = [];
enemies.forEach(e => scene.remove(e.mesh));
enemies = [];
// Reset player position if needed
if (player) {
player.position.set(0, 0.5, 5); // Slightly forward from camera's lookAt
}
}
function createPlayer() {
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshStandardMaterial({ color: 0x0077ff });
player = new THREE.Mesh(geometry, material);
player.position.y = 0.5; // Sit on the "ground"
scene.add(player);
}
// --- Gun Logic ---
function applyGunUpgrade() {
const upgrade = gunUpgrades[currentGunLevel];
player.material.color.setHex(upgrade.color || 0x0077ff); // Change player color with upgrade
updateUI();
}
function shoot() {
if (!gameRunning) return;
const now = Date.now();
const currentUpgrade = gunUpgrades[currentGunLevel];
if (now - lastShotTime < currentUpgrade.fireRate) return;
lastShotTime = now;
const bulletsPerShot = currentUpgrade.bulletsPerShot || 1;
const spreadAngle = currentUpgrade.spreadAngle || 0; // Degrees
for (let i = 0; i < bulletsPerShot; i++) {
const bulletGeo = new THREE.SphereGeometry(currentUpgrade.bulletSize, 8, 8);
const bulletMat = new THREE.MeshBasicMaterial({ color: currentUpgrade.color });
const bulletMesh = new THREE.Mesh(bulletGeo, bulletMat);
bulletMesh.position.copy(player.position);
// Calculate direction: from player towards where the camera is looking along the XZ plane
const direction = new THREE.Vector3();
camera.getWorldDirection(direction);
direction.y = 0; // Keep bullets on the XZ plane
direction.normalize();
// Apply spread
if (bulletsPerShot > 1) {
const angleOffset = (Math.random() - 0.5) * THREE.MathUtils.degToRad(spreadAngle);
direction.applyAxisAngle(new THREE.Vector3(0,1,0), angleOffset);
}
const bullet = {
mesh: bulletMesh,
velocity: direction.multiplyScalar(BULLET_SPEED),
damage: currentUpgrade.damage
};
bullets.push(bullet);
scene.add(bulletMesh);
}
}
// --- Enemy Logic ---
function spawnEnemy() {
if (!gameRunning) return;
const now = Date.now();
if (now - lastEnemySpawnTime > nextEnemySpawnInterval) {
lastEnemySpawnTime = now;
nextEnemySpawnInterval = THREE.MathUtils.randInt(ENEMY_SPAWN_INTERVAL_MIN, ENEMY_SPAWN_INTERVAL_MAX) / (1 + score / 5000); // Spawn faster as score increases
const enemyGeo = new THREE.SphereGeometry(0.75, 16, 16);
const enemyMat = new THREE.MeshStandardMaterial({ color: 0xff0000 });
const enemyMesh = new THREE.Mesh(enemyGeo, enemyMat);
// Spawn at random edge
const edge = Math.floor(Math.random() * 4);
const spawnDistance = 20;
let x, z;
if (edge === 0) { // Top
x = THREE.MathUtils.randFloatSpread(spawnDistance * 2);
z = -spawnDistance;
} else if (edge === 1) { // Bottom
x = THREE.MathUtils.randFloatSpread(spawnDistance * 2);
z = spawnDistance;
} else if (edge === 2) { // Left
x = -spawnDistance;
z = THREE.MathUtils.randFloatSpread(spawnDistance * 2);
} else { // Right
x = spawnDistance;
z = THREE.MathUtils.randFloatSpread(spawnDistance * 2);
}
enemyMesh.position.set(x, 0.75, z);
const scaledHP = ENEMY_BASE_HP * (1 + score / 2000); // HP scales with score
const enemy = {
mesh: enemyMesh,
hp: scaledHP,
maxHp: scaledHP,
speed: ENEMY_SPEED * (1 + score / 10000) // Speed scales slightly
};
enemies.push(enemy);
scene.add(enemyMesh);
}
}
// --- Game Loop and Updates ---
function update() {
if (!gameRunning) return;
// Player Movement
const moveDirection = new THREE.Vector3();
if (keys['w'] || keys['W'] || keys['ArrowUp']) moveDirection.z -= 1;
if (keys['s'] || keys['S'] || keys['ArrowDown']) moveDirection.z += 1;
if (keys['a'] || keys['A'] || keys['ArrowLeft']) moveDirection.x -= 1;
if (keys['d'] || keys['D'] || keys['ArrowRight']) moveDirection.x += 1;
moveDirection.normalize().multiplyScalar(PLAYER_SPEED);
player.position.add(moveDirection);
// Keep player within bounds (optional, but good for this camera setup)
player.position.x = THREE.MathUtils.clamp(player.position.x, -15, 15);
player.position.z = THREE.MathUtils.clamp(player.position.z, -15, 15);
// Update camera to follow player (simple follow)
camera.position.x = player.position.x;
camera.position.z = player.position.z + 10; // Maintain distance behind
camera.lookAt(player.position);
// Update Bullets
for (let i = bullets.length - 1; i >= 0; i--) {
const bullet = bullets[i];
bullet.mesh.position.add(bullet.velocity);
// Despawn bullets if they go too far
if (bullet.mesh.position.length() > 50) { // Arbitrary distance
scene.remove(bullet.mesh);
bullets.splice(i, 1);
}
}
// Update Enemies
for (let i = enemies.length - 1; i >= 0; i--) {
const enemy = enemies[i];
const directionToPlayer = new THREE.Vector3().subVectors(player.position, enemy.mesh.position).normalize();
enemy.mesh.position.add(directionToPlayer.multiplyScalar(enemy.speed));
// Enemy-Player collision (simple distance check)
if (enemy.mesh.position.distanceTo(player.position) < 1.25) { // Player radius 0.5 + Enemy radius 0.75
playerHP -= 10; // Damage player
if (playerHP <= 0) {
playerHP = 0;
gameOver();
}
// Remove enemy on collision
scene.remove(enemy.mesh);
enemies.splice(i, 1);
updateUI();
continue; // Skip further checks for this enemy
}
}
// Collision Detection: Bullet vs Enemy
for (let i = bullets.length - 1; i >= 0; i--) {
const bullet = bullets[i];
for (let j = enemies.length - 1; j >= 0; j--) {
const enemy = enemies[j];
const bulletRadius = gunUpgrades[currentGunLevel].bulletSize;
if (bullet.mesh.position.distanceTo(enemy.mesh.position) < bulletRadius + 0.75) { // Bullet radius + enemy radius
enemy.hp -= bullet.damage;
// Visual feedback for hit (e.g., flash red)
enemy.mesh.material.emissive.setHex(0xff0000);
setTimeout(() => {
if (enemy.mesh.material) enemy.mesh.material.emissive.setHex(0x000000);
}, 100);
if (enemy.hp <= 0) {
scene.remove(enemy.mesh);
enemies.splice(j, 1);
score += SCORE_PER_KILL;
checkGunUpgrade();
}
scene.remove(bullet.mesh);
bullets.splice(i, 1);
updateUI();
break; // Bullet can only hit one enemy
}
}
}
// Spawn new enemies
spawnEnemy();
}
function checkGunUpgrade() {
if (score >= nextUpgradeScore && currentGunLevel < gunUpgrades.length - 1) {
currentGunLevel++;
nextUpgradeScore += UPGRADE_SCORE_INTERVAL * (currentGunLevel + 1); // Increase cost for next
applyGunUpgrade();
// Simple visual/audio cue for upgrade could be added here
console.log(`Gun Upgraded to Level ${gunUpgrades[currentGunLevel].level}!`);
}
updateUI();
}
function updateUI() {
scoreDisplay.textContent = score;
playerHPDisplay.textContent = playerHP;
const currentUpgrade = gunUpgrades[currentGunLevel];
gunLevelDisplay.textContent = currentUpgrade.level;
gunDamageDisplay.textContent = currentUpgrade.damage;
fireRateDisplay.textContent = `${currentUpgrade.fireRate}ms`;
if (currentGunLevel < gunUpgrades.length - 1) {
nextUpgradeScoreDisplay.textContent = nextUpgradeScore;
} else {
nextUpgradeScoreDisplay.textContent = "MAX";
}
}
function gameOver() {
gameRunning = false;
finalScoreDisplay.textContent = score;
gameOverScreen.style.display = 'block';
// Potentially stop player movement, clear intervals etc.
}
function restartGame() {
gameRunning = true;
gameOverScreen.style.display = 'none';
resetPlayerState(); // Resets HP, score, gun level, clears entities
applyGunUpgrade(); // Sets up initial gun
updateUI();
// Re-initialize any timers or game state needed
lastEnemySpawnTime = Date.now(); // Reset spawn timer
nextEnemySpawnInterval = ENEMY_SPAWN_INTERVAL_MIN;
}
// --- Event Handlers ---
function onKeyDown(event) {
keys[event.key] = true;
if (event.code === 'Space') { // Allow space for shooting too
shoot();
}
}
function onKeyUp(event) {
keys[event.key] = false;
}
function onMouseDown(event) {
if (event.button === 0) { // Left mouse button
shoot();
}
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
// --- Animation Loop ---
function animate() {
requestAnimationFrame(animate);
if (gameRunning) {
update();
}
renderer.render(scene, camera);
}
// --- Start the game ---
init();
How to Run:
- Save the HTML as
index.html.
- Save the JavaScript as
game.js in the same directory.
- You'll need a simple local web server to run this due to ES6 module imports (
import * as THREE ...).
- If you have Python:
python -m http.server (Python 3) or python -m SimpleHTTPServer (Python 2) in the directory.
- Or use Node.js with
npx serve.
- Or use a VS Code extension like "Live Server".
- Open
http://localhost:8000 (or the port your server uses) in your browser.
Key Features Implemented:
- Three.js Setup: Scene, camera, renderer, basic lighting.
- Player:
- A blue cube.
- Moves with WASD or Arrow Keys.
- Has HP, displayed on UI.
- Camera follows the player.
- Shooting:
- Click left mouse button or press Space to shoot.
- Bullets are small spheres.
- Enemies:
- Red spheres.
- Spawn at random intervals from off-screen edges.
- Move towards the player.
- HP Scaling: Enemy HP increases based on the player's current score.
- Speed also slightly increases with score.
- Gun Upgrades:
- A predefined array
gunUpgrades holds different gun stats (damage, fireRate, color, bullet size, multi-shot).
- Player's gun upgrades automatically when a certain score threshold (
UPGRADE_SCORE_INTERVAL) is reached.
- Upgrades improve damage, fire rate, and can add multi-shot with spread.
- Player color changes with gun level.
- Combat:
- Bullets damage enemies.
- Enemies damage the player on contact.
- Simple distance-based collision detection.
- Endless Nature: Enemies keep spawning. Difficulty (enemy HP, spawn rate) increases over time (based on score).
- UI:
- Displays Score, Player HP, Gun Level, Damage, Fire Rate, and Score for Next Upgrade.
- Game Over & Restart:
- When player HP reaches 0, a "Game Over" screen appears.
- A "Restart" button allows starting a new game.
Potential Improvements (Beyond Scope of Initial Request but good next steps):
- Better Visuals: More interesting models, textures, particle effects for explosions/hits.
- Sound Effects: Shooting, hits, explosions, background music.
- Power-ups: Collectible items for temporary boosts or instant upgrades.
- More Enemy Types: Different behaviors, attack patterns.
- Bosses: Special, challenging enemies at certain score milestones.
- Object Pooling: For bullets and enemies to improve performance by reusing objects instead of constantly creating/destroying them.
- More Sophisticated Collision: Using Three.js's built-in
Box3 or physics engine.
- Player Aiming: Allow player to aim with mouse, not just shoot in camera direction.
- Ground/Environment: Add a textured plane or simple environment.
This code provides a solid foundation for an endless shooter in Three.js!