<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Enhanced Space Flight Simulator</title>
<style>
body { margin: 0; overflow: hidden; background: black; }
#info {
position: absolute;
top: 10px;
left: 10px;
color: white;
z-index: 1;
font-family: sans-serif;
line-height: 1.5;
}
</style>
</head>
<body>
<div id="info">
<b>Space Flight Simulator Enhanced</b><br>
WASD: Move<br>
Mouse: Look<br>
Space/Shift: Up/Down<br>
V: Toggle View (First/Third Person)<br>
Click to lock pointer
</div>
<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.155.0/build/three.module.js';
import { GLTFLoader } from 'https://cdn.jsdelivr.net/npm/three@0.155.0/examples/jsm/loaders/GLTFLoader.js';
// === Scene Setup ===
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x000010);
// Renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// === Starfield Background ===
const starGeometry = new THREE.BufferGeometry();
const starCount = 3000;
const starVertices = [];
for (let i = 0; i < starCount; i++) {
const x = (Math.random() - 0.5) * 4000;
const y = (Math.random() - 0.5) * 4000;
const z = (Math.random() - 0.5) * 4000;
starVertices.push(x, y, z);
}
starGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starVertices, 3));
const starMaterial = new THREE.PointsMaterial({ color: 0xffffff, size: 1 });
const stars = new THREE.Points(starGeometry, starMaterial);
scene.add(stars);
// === Lighting ===
const ambientLight = new THREE.AmbientLight(0x888888);
scene.add(ambientLight);
const pointLight = new THREE.PointLight(0xffffff, 1);
pointLight.position.set(10, 10, 10);
scene.add(pointLight);
// === Spaceship Loading ===
let spaceship;
const loader = new GLTFLoader();
loader.load(
'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Models/master/2.0/SciFiHelmet/glTF/SciFiHelmet.gltf',
function (gltf) {
spaceship = gltf.scene;
spaceship.scale.set(0.1, 0.1, 0.1); // Adjust scale
spaceship.rotation.x = Math.PI / 2;
scene.add(spaceship);
// Set default spaceship orientation
spaceship.rotation.order = 'YXZ'; // Important for mouse-look.
// The Spaceship Group
spacecraftGroup.add(spaceship);
},
function (xhr) {
console.log((xhr.loaded / xhr.total * 100) + '% loaded');
},
function (error) {
console.error('An error happened loading the spaceship model', error);
}
);
// === Spacecraft Group
const spacecraftGroup = new THREE.Group();
scene.add(spacecraftGroup);
// === Camera Setup ===
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 10000);
scene.add(camera);
// === View Mode ===
let viewMode = "third";
// === Controls State ===
let moveForward = false,
moveBackward = false,
moveLeft = false,
moveRight = false,
moveUp = false,
moveDown = false;
let canControl = false;
let pitch = 0, yaw = 0;
// === Pointer Lock ===
renderer.domElement.addEventListener('click', () => {
renderer.domElement.requestPointerLock();
});
document.addEventListener('pointerlockchange', () => {
canControl = (document.pointerLockElement === renderer.domElement);
});
document.addEventListener('mousemove', (event) => {
if (!canControl) return;
yaw -= event.movementX * 0.002;
pitch -= event.movementY * 0.002;
pitch = Math.max(-Math.PI / 2, Math.min(Math.PI / 2, pitch));
});
// === Keyboard Handling ===
document.addEventListener('keydown', (event) => {
switch (event.code) {
case 'KeyW': moveForward = true; break;
case 'KeyS': moveBackward = true; break;
case 'KeyA': moveLeft = true; break;
case 'KeyD': moveRight = true; break;
case 'Space': moveUp = true; break;
case 'ShiftLeft': moveDown = true; break;
case 'KeyV':
viewMode = (viewMode === "third") ? "first" : "third";
break;
}
});
document.addEventListener('keyup', (event) => {
switch (event.code) {
case 'KeyW': moveForward = false; break;
case 'KeyS': moveBackward = false; break;
case 'KeyA': moveLeft = false; break;
case 'KeyD': moveRight = false; break;
case 'Space': moveUp = false; break;
case 'ShiftLeft': moveDown = false; break;
}
});
// === Space Objects ===
let spaceObjects = [];
// Create space object
function createSpaceObject() {
const type = Math.random() < 0.5 ? "planet" : "asteroid";
let object;
if (type === "planet") {
const radius = Math.random() * 5 + 2; // radius between 2 and 7
const detail = Math.floor(Math.random() * 4) + 3; // random detail levels
const geometry = new THREE.IcosahedronGeometry(radius, detail);
const color = new THREE.Color(Math.random(), Math.random(), Math.random());
const material = new THREE.MeshPhongMaterial({ color: color, flatShading: true });
object = new THREE.Mesh(geometry, material);
object.userData = { type: 'planet', radius: radius };
} else {
// Asteroid: non-uniform scale
const radius = Math.random() * 3 + 1;
const geometry = new THREE.IcosahedronGeometry(radius, 1);
const material = new THREE.MeshPhongMaterial({ color: 0x888888, flatShading: true });
object = new THREE.Mesh(geometry, material);
object.scale.set(Math.random() + 0.5, Math.random() + 0.5, Math.random() + 0.5);
object.userData = { type: 'asteroid', radius: radius };
}
return object;
}
// Spawn space objects around
function spawnSpaceObjectsAround(position, count = 10, minDist = 50, maxDist = 500) {
for (let i = 0; i < count; i++) {
const obj = createSpaceObject();
const theta = Math.acos(THREE.MathUtils.randFloatSpread(2));
const phi = THREE.MathUtils.randFloat(0, Math.PI * 2);
const distance = THREE.MathUtils.randFloat(minDist, maxDist);
const x = position.x + distance * Math.sin(theta) * Math.cos(phi);
const y = position.y + distance * Math.sin(theta) * Math.sin(phi);
const z = position.z + distance * Math.cos(theta);
obj.position.set(x, y, z);
scene.add(obj);
spaceObjects.push(obj);
}
}
// Initialize space objects
spawnSpaceObjectsAround(spacecraftGroup.position, 30);
// === Animation Loop ===
function animate() {
requestAnimationFrame(animate);
// --- Control Movement Direction ---
const moveDir = new THREE.Vector3();
if (moveForward) moveDir.z -= 1;
if (moveBackward) moveDir.z += 1;
if (moveLeft) moveDir.x -= 1;
if (moveRight) moveDir.x += 1;
if (moveUp) moveDir.y += 1;
if (moveDown) moveDir.y -= 1;
if (moveDir.lengthSq() > 0) {
moveDir.normalize();
}
// --- Spaceship Movement and Rotation ---
spacecraftGroup.rotation.order = 'YXZ';
spacecraftGroup.rotation.y = yaw;
spacecraftGroup.rotation.x = pitch;
const speed = 1;
const localMove = moveDir.clone().applyEuler(spacecraftGroup.rotation);
spacecraftGroup.position.add(localMove.multiplyScalar(speed));
// --- Update Camera Position ---
if (spaceship) {
if (viewMode === "third") {
// Third-Person View (Camera behind spaceship)
const thirdOffset = new THREE.Vector3(0, 3, 10);
thirdOffset.applyEuler(spacecraftGroup.rotation);
camera.position.copy(spacecraftGroup.position).add(thirdOffset);
camera.lookAt(spacecraftGroup.position);
} else {
// First-Person View (Camera inside spaceship)
const firstOffset = new THREE.Vector3(0, 0.5, 0);
firstOffset.applyEuler(spacecraftGroup.rotation);
camera.position.copy(spacecraftGroup.position).add(firstOffset);
// Look forward (adjust as needed)
const forward = new THREE.Vector3(0, 0, -1);
forward.applyEuler(spacecraftGroup.rotation);
camera.lookAt(camera.position.clone().add(forward));
}
}
// --- Object Management ---
const currentPos = spacecraftGroup.position;
spaceObjects = spaceObjects.filter(obj => {
if (obj.position.distanceTo(currentPos) > 600) {
scene.remove(obj);
return false;
}
return true;
});
if (spaceObjects.length < 30) {
spawnSpaceObjectsAround(currentPos, 10);
}
renderer.render(scene, camera);
}
animate();
// === Handle Window Resize ===
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>
Key changes:
- New GLTF Loader: The code imports
GLTFLoader to load more complex models in glTF format.
- Model Loading: I've used a Sci-Fi Helmet model from the Khronos Group glTF sample models, which is available here: https://github.com/KhronosGroup/glTF-Sample-Models/tree/master/2.0/SciFiHelmet/glTF. You'll see the code load this model and apply it to the scene. If you want a different model, you'll need to find a
.gltf file online and replace the URL in the loader.load() function. A great resource for free glTF models is Sketchfab.
- Object Types: Planets now use
IcosahedronGeometry (which is like a smoother version of the original "polygon" look). They have a random detail level for varied geometry.
- Randomized Detail: Random detail levels are added to planets using IcosahedronGeometry for non-uniform, and more realistic asteroid shapes.
- Non-Uniform Scale: Asteroids have random scale applied on different axes to look less uniform.
Remember to include the GLTFLoader module in your HTML. If you're running this locally, you'll probably need to use a local web server (like the one provided by Python with python -m http.server) for the model to load correctly.