Of course! Here is a complete, single-file HTML game called "Asteroid Intercept" that meets all your requirements.
This file includes:
- HTML Structure: Basic layout with a canvas and UI overlay elements.
- CSS Styling: Styles for the UI, game-over screen, and a targeting reticle.
- JavaScript Logic: All game mechanics using Three.js.
Simply copy the code below, save it as an .html file, and open it in a modern web browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Asteroid Intercept</title>
<style>
/* Basic CSS Reset and Setup */
body {
margin: 0;
overflow: hidden;
background-color: #000;
color: #fff;
font-family: 'Courier New', Courier, monospace;
}
canvas {
display: block;
}
/* UI Overlay Elements */
#ui-container {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none; /* Allows clicks to pass through to the canvas */
text-shadow: 2px 2px 4px #000;
}
#score {
position: absolute;
top: 20px;
left: 20px;
font-size: 2em;
}
#instructions {
position: absolute;
bottom: 20px;
width: 100%;
text-align: center;
font-size: 1.2em;
}
/* Game Over Screen */
#game-over-screen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.75);
display: none; /* Hidden by default */
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
pointer-events: auto; /* Re-enable pointer events for the button */
}
#game-over-screen h1 {
font-size: 4em;
margin: 0;
color: #ff4444;
}
#game-over-screen p {
font-size: 2em;
}
#restart-button {
padding: 15px 30px;
font-size: 1.5em;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
margin-top: 20px;
font-family: 'Courier New', Courier, monospace;
}
#restart-button:hover {
background-color: #45a049;
}
/* Targeting Reticle (CSS based for simplicity) */
#reticle {
position: absolute;
width: 20px;
height: 20px;
border: 2px solid #00ff00;
border-radius: 50%;
transform: translate(-50%, -50%);
pointer-events: none;
}
#reticle::before, #reticle::after {
content: '';
position: absolute;
background-color: #00ff00;
}
#reticle::before { /* Vertical line */
width: 2px;
height: 30px;
left: 9px;
top: -5px;
}
#reticle::after { /* Horizontal line */
width: 30px;
height: 2px;
left: -5px;
top: 9px;
}
</style>
</head>
<body>
<!-- UI Elements -->
<div id="ui-container">
<div id="score">Score: 0</div>
<div id="instructions">Use mouse to aim, Click to fire. Defend the planet!</div>
<div id="game-over-screen">
<h1>GAME OVER</h1>
<p id="final-score"></p>
<button id="restart-button">Restart</button>
</div>
</div>
<div id="reticle"></div>
<!-- Three.js CDN Imports -->
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}
}
</script>
<!-- Main Game Logic -->
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// --- SCENE SETUP ---
let scene, camera, renderer, controls, clock;
let planet;
// --- GAME STATE ---
let score = 0;
let isGameOver = false;
let asteroids = [];
let missiles = [];
let explosions = [];
// --- GAME CONSTANTS ---
const PLANET_RADIUS = 25;
const ASTEROID_SPAWN_RADIUS = 200;
const ASTEROID_SPEED_MIN = 5;
const ASTEROID_SPEED_MAX = 10;
const MISSILE_SPEED = 150;
const COLLISION_THRESHOLD = {
asteroid_planet: PLANET_RADIUS + 5, // Asteroid radius is ~5
missile_asteroid: 1 + 5
};
// --- UI ELEMENTS ---
const scoreElement = document.getElementById('score');
const gameOverScreen = document.getElementById('game-over-screen');
const finalScoreElement = document.getElementById('final-score');
const restartButton = document.getElementById('restart-button');
const reticleElement = document.getElementById('reticle');
// --- INITIALIZATION ---
function init() {
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x000005);
// Camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 100;
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
document.body.appendChild(renderer.domElement);
// Clock
clock = new THREE.Clock();
// Lighting
const ambientLight = new THREE.AmbientLight(0x404040, 1.5); // soft white light
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.5);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
// Controls
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.minDistance = 50;
controls.maxDistance = 300;
// Create Game Objects
createStarfield();
createPlanet();
// Event Listeners
window.addEventListener('resize', onWindowResize);
window.addEventListener('click', onMouseClick);
window.addEventListener('mousemove', onMouseMove);
restartButton.addEventListener('click', restartGame);
// Start Asteroid Spawning
setInterval(spawnAsteroid, 3000);
}
// --- OBJECT CREATION ---
function createStarfield() {
const starVertices = [];
for (let i = 0; i < 10000; i++) {
const x = THREE.MathUtils.randFloatSpread(2000);
const y = THREE.MathUtils.randFloatSpread(2000);
const z = THREE.MathUtils.randFloatSpread(2000);
starVertices.push(x, y, z);
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starVertices, 3));
const starMaterial = new THREE.PointsMaterial({ color: 0xffffff, size: 0.5, sizeAttenuation: true });
const stars = new THREE.Points(starGeometry, starMaterial);
scene.add(stars);
}
function createPlanet() {
const planetGeometry = new THREE.SphereGeometry(PLANET_RADIUS, 64, 64);
// Procedural texture using a canvas
const canvas = document.createElement('canvas');
canvas.width = 256;
canvas.height = 128;
const context = canvas.getContext('2d');
// Blue water base
context.fillStyle = '#1565C0'; // A nice deep blue
context.fillRect(0, 0, 256, 128);
// Green/brown landmasses
context.fillStyle = '#2E7D32'; // A lush green
for (let i = 0; i < 500; i++) {
const x = Math.random() * 256;
const y = Math.random() * 128;
const size = Math.random() * 3 + 1;
context.fillRect(x, y, size, size);
}
context.fillStyle = '#6D4C41'; // Brownish color
for (let i = 0; i < 200; i++) {
const x = Math.random() * 256;
const y = Math.random() * 128;
const size = Math.random() * 2 + 1;
context.fillRect(x, y, size, size);
}
const planetTexture = new THREE.CanvasTexture(canvas);
planetTexture.wrapS = THREE.RepeatWrapping;
planetTexture.wrapT = THREE.RepeatWrapping;
planetTexture.anisotropy = renderer.capabilities.getMaxAnisotropy();
const planetMaterial = new THREE.MeshStandardMaterial({
map: planetTexture,
roughness: 0.8,
metalness: 0.1
});
planet = new THREE.Mesh(planetGeometry, planetMaterial);
scene.add(planet);
}
function spawnAsteroid() {
if (isGameOver) return;
// Irregular shape using Icosahedron and vertex displacement
const geometry = new THREE.IcosahedronGeometry(5, 1);
const positionAttribute = geometry.getAttribute('position');
const vertex = new THREE.Vector3();
for (let i = 0; i < positionAttribute.count; i++) {
vertex.fromBufferAttribute(positionAttribute, i);
vertex.multiplyScalar(1 + Math.random() * 0.4); // Displace vertices
positionAttribute.setXYZ(i, vertex.x, vertex.y, vertex.z);
}
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
color: 0x8B4513, // Brownish
roughness: 0.9,
metalness: 0.2
});
const asteroid = new THREE.Mesh(geometry, material);
// Spawn at a random point on a sphere outside the view
const spawnPoint = new THREE.Vector3()
.randomDirection()
.multiplyScalar(ASTEROID_SPAWN_RADIUS);
asteroid.position.copy(spawnPoint);
// Aim it at the planet with some randomness
const velocity = new THREE.Vector3()
.subVectors(planet.position, asteroid.position)
.normalize()
.multiplyScalar(THREE.MathUtils.randFloat(ASTEROID_SPEED_MIN, ASTEROID_SPEED_MAX));
// Add a little random sideways vector to avoid perfect aim every time
const randomOffset = new THREE.Vector3().randomDirection().multiplyScalar(2);
velocity.add(randomOffset);
asteroids.push({ mesh: asteroid, velocity: velocity });
scene.add(asteroid);
}
function launchMissile(targetVector) {
const geometry = new THREE.CapsuleGeometry(0.5, 3, 4, 8);
const material = new THREE.MeshBasicMaterial({ color: 0x00ffff, emissive: 0x00ffff });
const missile = new THREE.Mesh(geometry, material);
// Start near the camera
missile.position.copy(camera.position);
// Orient the missile to face the target
missile.lookAt(targetVector);
const velocity = new THREE.Vector3()
.subVectors(targetVector, missile.position)
.normalize()
.multiplyScalar(MISSILE_SPEED);
missiles.push({ mesh: missile, velocity: velocity });
scene.add(missile);
}
function createExplosion(position) {
const explosionGeometry = new THREE.BufferGeometry();
const vertices = [];
const velocities = [];
const colors = [];
const explosionColor = new THREE.Color();
for (let i = 0; i < 50; i++) {
vertices.push(0, 0, 0); // Start all particles at the explosion center
const velocity = new THREE.Vector3(
(Math.random() - 0.5),
(Math.random() - 0.5),
(Math.random() - 0.5)
).normalize().multiplyScalar(Math.random() * 50);
velocities.push(velocity);
explosionColor.setHSL(Math.random() * 0.1 + 0.05, 1.0, 0.5); // Orange/Yellow
colors.push(explosionColor.r, explosionColor.g, explosionColor.b);
}
explosionGeometry.setAttribute('position', new THREE.Float32BufferAttribute(vertices, 3));
explosionGeometry.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3));
const material = new THREE.PointsMaterial({
size: 1,
vertexColors: true,
blending: THREE.AdditiveBlending,
transparent: true,
depthWrite: false,
});
const particles = new THREE.Points(explosionGeometry, material);
particles.position.copy(position);
explosions.push({ particles: particles, velocities: velocities, life: 1.0 });
scene.add(particles);
}
// --- GAME LOOP & UPDATES ---
function animate() {
requestAnimationFrame(animate);
const deltaTime = clock.getDelta();
if (!isGameOver) {
updateAsteroids(deltaTime);
updateMissiles(deltaTime);
checkCollisions();
// Planet rotation
planet.rotation.y += 0.05 * deltaTime;
}
updateExplosions(deltaTime);
controls.update();
renderer.render(scene, camera);
}
function updateAsteroids(dt) {
for (const asteroid of asteroids) {
asteroid.mesh.position.add(asteroid.velocity.clone().multiplyScalar(dt));
asteroid.mesh.rotation.x += 0.5 * dt;
asteroid.mesh.rotation.y += 0.5 * dt;
}
}
function updateMissiles(dt) {
for (const missile of missiles) {
missile.mesh.position.add(missile.velocity.clone().multiplyScalar(dt));
}
}
function updateExplosions(dt) {
for (let i = explosions.length - 1; i >= 0; i--) {
const explosion = explosions[i];
explosion.life -= dt * 1.5; // Explosions last about 0.66 seconds
if (explosion.life <= 0) {
// Remove from scene and array
scene.remove(explosion.particles);
explosion.particles.geometry.dispose();
explosion.particles.material.dispose();
explosions.splice(i, 1);
} else {
// Update particle positions
const positions = explosion.particles.geometry.attributes.position;
for (let j = 0; j < positions.count; j++) {
const vx = explosion.velocities[j].x;
const vy = explosion.velocities[j].y;
const vz = explosion.velocities[j].z;
positions.setXYZ(
j,
positions.getX(j) + vx * dt,
positions.getY(j) + vy * dt,
positions.getZ(j) + vz * dt
);
}
positions.needsUpdate = true;
// Fade out
explosion.particles.material.opacity = explosion.life;
}
}
}
// --- COLLISION DETECTION ---
function checkCollisions() {
// Asteroid vs Planet
for (let i = asteroids.length - 1; i >= 0; i--) {
const asteroid = asteroids[i];
if (asteroid.mesh.position.length() < COLLISION_THRESHOLD.asteroid_planet) {
endGame();
// Create a large explosion on the planet
const impactPosition = asteroid.mesh.position.clone().normalize().multiplyScalar(PLANET_RADIUS);
createExplosion(impactPosition);
// Remove the asteroid
removeObject(asteroid.mesh);
asteroids.splice(i, 1);
return; // Stop checking after game over
}
}
// Missile vs Asteroid
for (let i = missiles.length - 1; i >= 0; i--) {
const missile = missiles[i];
let missileHit = false;
for (let j = asteroids.length - 1; j >= 0; j--) {
const asteroid = asteroids[j];
if (missile.mesh.position.distanceTo(asteroid.mesh.position) < COLLISION_THRESHOLD.missile_asteroid) {
// HIT!
createExplosion(asteroid.mesh.position);
// Remove both
removeObject(asteroid.mesh);
asteroids.splice(j, 1);
removeObject(missile.mesh);
missiles.splice(i, 1);
// Update score
score++;
scoreElement.innerText = `Score: ${score}`;
missileHit = true;
break; // Missile can only hit one asteroid
}
}
// Also check if missile flew too far
if (!missileHit && missile.mesh.position.length() > ASTEROID_SPAWN_RADIUS * 2) {
removeObject(missile.mesh);
missiles.splice(i, 1);
}
}
}
// --- GAME STATE & UI MANAGEMENT ---
function endGame() {
isGameOver = true;
gameOverScreen.style.display = 'flex';
finalScoreElement.innerText = `Final Score: ${score}`;
}
function restartGame() {
// Reset state
isGameOver = false;
score = 0;
scoreElement.innerText = `Score: 0`;
gameOverScreen.style.display = 'none';
// Clean up all dynamic objects
[...asteroids, ...missiles].forEach(obj => removeObject(obj.mesh));
explosions.forEach(exp => removeObject(exp.particles));
asteroids = [];
missiles = [];
explosions = [];
// Reset camera if needed
camera.position.set(0, 0, 100);
controls.target.set(0, 0, 0);
}
// --- UTILITY & EVENT HANDLERS ---
function removeObject(obj) {
if (!obj) return;
scene.remove(obj);
if (obj.geometry) obj.geometry.dispose();
if (obj.material) {
// For materials with maps, dispose the texture too
if (obj.material.map) obj.material.map.dispose();
obj.material.dispose();
}
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onMouseClick(event) {
if (isGameOver) return;
// Get 3D point of the click
const mouse = new THREE.Vector2(
(event.clientX / window.innerWidth) * 2 - 1,
-(event.clientY / window.innerHeight) * 2 + 1
);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
// Create a virtual plane to intersect with, at a reasonable distance
const plane = new THREE.Plane(new THREE.Vector3(0, 0, 1), -100);
plane.applyMatrix4(camera.matrixWorld); // Orient plane relative to camera
const targetPoint = new THREE.Vector3();
raycaster.ray.intersectPlane(plane, targetPoint);
// If the intersection is behind the camera, just aim far along the ray
if (!targetPoint) {
raycaster.ray.at(1000, targetPoint);
}
launchMissile(targetPoint);
}
function onMouseMove(event) {
// Update the CSS reticle's position
reticleElement.style.left = `${event.clientX}px`;
reticleElement.style.top = `${event.clientY}px`;
}
// --- START THE GAME ---
init();
animate();
</script>
</body>
</html>