html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Basic Flight Simulator</title>
<style>
body {
margin: 0;
overflow: hidden;
font-family: Arial, sans-serif;
}
canvas {
display: block;
background: linear-gradient(#87CEEB, #E0F7FF);
}
#hud {
position: absolute;
bottom: 20px;
left: 20px;
color: white;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 5px;
font-family: monospace;
}
#controls {
position: absolute;
top: 20px;
right: 20px;
color: white;
background-color: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 5px;
font-family: monospace;
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<div id="hud">
Speed: 0 | Altitude: 0 | X: 0 | Z: 0
</div>
<div id="controls">
W/S: Pitch | A/D: Roll | Q/E: Yaw<br>
Arrow Up/Down: Speed | Space: Reset
</div>
<script>
// Canvas setup
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Game state
const state = {
// Aircraft position and orientation
x: 0,
y: 100,
z: 0,
pitch: 0,
roll: 0,
yaw: 0,
speed: 0,
// Camera
cameraDistance: 10,
cameraHeight: 5,
// Controls
keys: {},
// World
buildings: [],
worldSize: 5000,
groundColor: '#8B4513',
// Game loop
lastTime: 0,
deltaTime: 0
};
// Generate buildings
function generateBuildings() {
const buildingCount = 200;
const buildings = [];
for (let i = 0; i < buildingCount; i++) {
const x = (Math.random() * 2 - 1) * state.worldSize;
const z = (Math.random() * 2 - 1) * state.worldSize;
const height = 50 + Math.random() * 200;
const width = 30 + Math.random() * 70;
const depth = 30 + Math.random() * 70;
const color = `rgb(${100 + Math.random() * 155}, ${100 + Math.random() * 155}, ${100 + Math.random() * 155})`;
buildings.push({ x, z, height, width, depth, color });
}
return buildings;
}
// 3D to 2D projection
function project(x, y, z) {
// Simple perspective projection
const fov = 90;
const aspectRatio = canvas.width / canvas.height;
const scale = canvas.height / 2;
// Translate to camera space
const dx = x - state.x;
const dy = y - state.y;
const dz = z - state.z;
// Rotate based on aircraft orientation
const cosYaw = Math.cos(state.yaw);
const sinYaw = Math.sin(state.yaw);
const cosPitch = Math.cos(state.pitch);
const sinPitch = Math.sin(state.pitch);
const cosRoll = Math.cos(state.roll);
const sinRoll = Math.sin(state.roll);
// Apply yaw rotation
let rx = dx * cosYaw - dz * sinYaw;
let rz = dx * sinYaw + dz * cosYaw;
// Apply pitch rotation
let ry = dy * cosPitch - rz * sinPitch;
rz = dy * sinPitch + rz * cosPitch;
// Apply roll rotation
const finalX = rx * cosRoll - ry * sinRoll;
const finalY = rx * sinRoll + ry * cosRoll;
const finalZ = rz;
// Perspective projection
if (finalZ <= 0) return null; // Behind camera
const projX = (finalX / finalZ) * scale + canvas.width / 2;
const projY = (finalY / finalZ) * scale + canvas.height / 2;
return { x: projX, y: projY, z: finalZ };
}
// Draw a building
function drawBuilding(building) {
const { x, z, height, width, depth, color } = building;
// Define building vertices
const vertices = [
// Front face (bottom)
{ x: x - width/2, y: 0, z: z - depth/2 },
{ x: x + width/2, y: 0, z: z - depth/2 },
{ x: x + width/2, y: 0, z: z + depth/2 },
{ x: x - width/2, y: 0, z: z + depth/2 },
// Front face (top)
{ x: x - width/2, y: height, z: z - depth/2 },
{ x: x + width/2, y: height, z: z - depth/2 },
{ x: x + width/2, y: height, z: z + depth/2 },
{ x: x - width/2, y: height, z: z + depth/2 }
];
// Project vertices to 2D
const projectedVertices = vertices.map(v => project(v.x, v.y, v.z)).filter(v => v !== null);
if (projectedVertices.length < 3) return; // Not enough visible vertices
// Define faces (each face is a list of vertex indices)
const faces = [
[0, 1, 5, 4], // Front
[1, 2, 6, 5], // Right
[2, 3, 7, 6], // Back
[3, 0, 4, 7], // Left
[4, 5, 6, 7] // Top
];
// Draw each face
for (const face of faces) {
const faceVertices = face.map(i => projectedVertices[i]).filter(v => v !== undefined);
if (faceVertices.length < 3) continue;
ctx.beginPath();
ctx.moveTo(faceVertices[0].x, faceVertices[0].y);
for (let i = 1; i < faceVertices.length; i++) {
ctx.lineTo(faceVertices[i].x, faceVertices[i].y);
}
ctx.closePath();
// Shade based on distance
const avgZ = faceVertices.reduce((sum, v) => sum + v.z, 0) / faceVertices.length;
const shade = Math.min(1, 5000 / avgZ);
ctx.fillStyle = color;
ctx.globalAlpha = shade;
ctx.fill();
ctx.globalAlpha = 1;
ctx.strokeStyle = '#000';
ctx.stroke();
}
}
// Draw ground grid
function drawGround() {
const gridSize = 200;
const gridExtent = state.worldSize;
// Draw ground plane
for (let x = -gridExtent; x <= gridExtent; x += gridSize) {
for (let z = -gridExtent; z <= gridExtent; z += gridSize) {
const corners = [
{ x: x, y: 0, z: z },
{ x: x + gridSize, y: 0, z: z },
{ x: x + gridSize, y: 0, z: z + gridSize },
{ x: x, y: 0, z: z + gridSize }
];
const projectedCorners = corners.map(c => project(c.x, c.y, c.z)).filter(c => c !== null);
if (projectedCorners.length < 3) continue;
ctx.beginPath();
ctx.moveTo(projectedCorners[0].x, projectedCorners[0].y);
for (let i = 1; i < projectedCorners.length; i++) {
ctx.lineTo(projectedCorners[i].x, projectedCorners[i].y);
}
ctx.closePath();
// Alternate colors for checkerboard pattern
const isEven = (Math.floor(x / gridSize) + Math.floor(z / gridSize)) % 2 === 0;
ctx.fillStyle = isEven ? '#7CFC00' : '#228B22';
// Fade with distance
const avgZ = projectedCorners.reduce((sum, c) => sum + c.z, 0) / projectedCorners.length;
const fade = Math.min(1, 5000 / avgZ);
ctx.globalAlpha = fade;
ctx.fill();
ctx.globalAlpha = 1;
}
}
}
// Update game state
function update() {
// Calculate delta time
const currentTime = performance.now();
state.deltaTime = (currentTime - state.lastTime) / 1000; // Convert to seconds
state.lastTime = currentTime;
// Handle controls
const rotationSpeed = 1 * state.deltaTime;
const accelerationRate = 50 * state.deltaTime;
// Pitch (W/S)
if (state.keys['KeyW']) state.pitch -= rotationSpeed;
if (state.keys['KeyS']) state.pitch += rotationSpeed;
// Roll (A/D)
if (state.keys['KeyA']) state.roll -= rotationSpeed;
if (state.keys['KeyD']) state.roll += rotationSpeed;
// Yaw (Q/E)
if (state.keys['KeyQ']) state.yaw -= rotationSpeed;
if (state.keys['KeyE']) state.yaw += rotationSpeed;
// Speed (Arrow Up/Down)
if (state.keys['ArrowUp']) state.speed += accelerationRate;
if (state.keys['ArrowDown']) state.speed -= accelerationRate;
// Limit speed
state.speed = Math.max(0, Math.min(500, state.speed));
// Reset (Space)
if (state.keys['Space']) {
state.x = 0;
state.y = 100;
state.z = 0;
state.pitch = 0;
state.roll = 0;
state.yaw = 0;
state.speed = 0;
}
// Apply physics
const gravity = 9.8;
// Move based on orientation and speed
const forwardX = Math.sin(state.yaw) * Math.cos(state.pitch);
const forwardY = -Math.sin(state.pitch);
const forwardZ = Math.cos(state.yaw) * Math.cos(state.pitch);
state.x += forwardX * state.speed * state.deltaTime;
state.y += forwardY * state.speed * state.deltaTime;
state.z += forwardZ * state.speed * state.deltaTime;
// Apply gravity if not moving fast enough
if (state.speed < 50 && state.y > 0) {
state.y -= gravity * state.deltaTime;
}
// Prevent going below ground
if (state.y < 0) {
state.y = 0;
state.pitch = 0;
}
// Wrap around world boundaries
const boundary = state.worldSize;
if (state.x > boundary) state.x = -boundary;
if (state.x < -boundary) state.x = boundary;
if (state.z > boundary) state.z = -boundary;
if (state.z < -boundary) state.z = boundary;
// Update HUD
document.getElementById('hud').textContent =
`Speed: ${Math.round(state.speed)} | Altitude: ${Math.round(state.y)} | X: ${Math.round(state.x)} | Z: ${Math.round(state.z)}`;
}
// Render the scene
function render() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw ground
drawGround();
// Sort buildings by distance (for proper depth rendering)
const sortedBuildings = [...state.buildings].sort((a, b) => {
const distA = Math.sqrt((a.x - state.x) ** 2 + (a.z - state.z) ** 2);
const distB = Math.sqrt((b.x - state.x) ** 2 + (b.z - state.z) ** 2);
return distB - distA; // Draw far buildings first
});
// Draw buildings
for (const building of sortedBuildings) {
drawBuilding(building);
}
}
// Game loop
function gameLoop() {
update();
render();
requestAnimationFrame(gameLoop);
}
// Handle keyboard input
window.addEventListener('keydown', (e) => {
state.keys[e.code] = true;
});
window.addEventListener('keyup', (e) => {
state.keys[e.code] = false;
});
// Handle window resize
window.addEventListener('resize', () => {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
});
// Initialize game
state.buildings = generateBuildings();
state.lastTime = performance.now();
gameLoop();
</script>
</body>
</html>