
Flight simulator
You fly an aircraft with controls modelled on the real thing: taking off, navigating and landing while minding the instruments, the weather and flight physics. It ranges from highly realistic simulation to arcade-style air combat.
Also known as: flight sim, flight simulation game
This is a basic entry: it has the definition and the classification. Full entries add history, games and a demo.
Our demo
Controls. Arrows or WASD: left and right bank (tilt the plane to turn); down or S raises the nose and up or W lowers it. E or Shift raise the throttle and Q or Ctrl lower it. Space to start. On mobile, the on-screen buttons: ◀ ▶ bank, ▲ ▼ nose, + − throttle.
Open full screenA simple 3D plane with an honest flight model: the engine gives speed, banking makes you turn and the wings only hold the plane up if it is fast enough. You take off from a runway, fly through a series of rings and land again without crashing. It is made with threeplay, a 3D engine in the spirit of Kaplay.
Made with threeplay, in about 186 lines of JavaScript.
How it's made
Setup and flight constants
The game is created at 640×360, the virtual buttons are defined (the mobile ones press the same) and so are the constants that give the plane its character. THRUST and DRAG set the top speed, STALL is the speed below which the wings stop carrying the plane, and the runway measures are used when landing. Changing STALL or THRUST turns the plane into a clumsy glider or a twitchy fighter.
const k = threeplay({ width: 640, height: 360, letterbox: true, background: "#9ad1f0", buttons: { left: { keyboard: ["left", "a"] }, right: { keyboard: ["right", "d"] }, nose_down: { keyboard: ["up", "w"] }, nose_up: { keyboard: ["down", "s"] }, faster: { keyboard: ["e", "shift"] }, slower: { keyboard: ["q", "ctrl"] }, start: { keyboard: ["space", "enter"] }, }, }); touchControls(k, [ { button: "left", label: "◀" }, { button: "nose_down", label: "▲" }, { button: "nose_up", label: "▼" }, { button: "right", label: "▶" }, { button: "faster", label: "+", side: "right" }, { button: "slower", label: "−", side: "right" }, ]); const G = 9.8; const THRUST = 8; // acceleration at full throttle const DRAG = 0.005; // drag grows with speed squared: top speed = sqrt(THRUST / DRAG) const STALL = 20; // below this speed the wings do not carry the plane const GROUND_Y = 0.9; // height of the plane's center when the wheels touch the ground const RUNWAY = { halfWidth: 8, from: 40, to: -200 }; // z range; the runway lies along z const STEP = 1 / 60;The world and the course
RINGS is the course list: position, altitude and heading of every ring. It is designed as a loop that ends in a final approach to the runway, which teaches you to plan your turns. The ground is a plane, the runway a striped box, and trees and hills are cones placed with a fixed-seed random number generator so the map is always the same. setFog() hides the horizon and gives depth.
// [x, altitude, z, heading in degrees]: the course is a loop that ends in a final approach. const RINGS = [ [0, 18, -210, 0], [0, 32, -340, 0], [-180, 45, -420, 90], [-300, 45, -150, 180], [-90, 35, 250, 270], [0, 22, 130, 0], ]; function buildWorld() { setFog({ color: "#9ad1f0", near: 150, far: 900 }); add([plane(6000, 6000), pos(0, 0, 0), color("#7bb661")]); const length = RUNWAY.from - RUNWAY.to; add([box(RUNWAY.halfWidth * 2, 0.1, length), pos(0, 0.05, (RUNWAY.from + RUNWAY.to) / 2), color("#4a4e57")]); for (let z = RUNWAY.from - 10; z > RUNWAY.to; z -= 20) add([box(0.6, 0.12, 8), pos(0, 0.1, z), color("#f1f1f1")]); // Trees and far hills are decoration: they give a sense of speed and depth. A fixed seed keeps the map the same. let seed = 7; const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647; for (let i = 0; i < 160; i++) { const x = (random() - 0.5) * 1400 - 150; const z = (random() - 0.5) * 1400 - 100; if (Math.abs(x) < 25 && z < RUNWAY.from + 20 && z > RUNWAY.to - 20) continue; add([cone(3 + random() * 3, 10 + random() * 8), pos(x, 6, z), color("#2d6a4f")]); } for (let i = 0; i < 12; i++) { const a = (i / 12) * Math.PI * 2; add([cone(120, 90 + (i % 3) * 40), pos(Math.cos(a) * 1100 - 150, 60, Math.sin(a) * 1100 - 100), color("#8d99ae")]); } }The plane and its state
The plane is an empty object with four child boxes (fuselage, wings, tail and fin). Its flight state lives in an object f: speed, throttle, heading, pitch, roll and vy, the extra fall caused by missing lift. It does not use body() or Rapier: the physics is custom because a flight model is a formula, not a collision between bodies. With rotate() and rotOrder = «YXZ», rot applies heading first, then pitch, then roll, as in a real plane.
// A plane is a few boxes. Nose points to -Z; rotation is yaw, then pitch, then roll. const body3d = add([pos(0, GROUND_Y, 30), rotate(), "plane"]); body3d.rotOrder = "YXZ"; // rot reads as heading (y), pitch (x) and roll (z) const parts = [ [0.8, 0.8, 4, 0, 0, 0, "#e63946"], // fuselage [7, 0.15, 1.2, 0, 0.1, -0.2, "#f1f1f1"], // wings [2.2, 0.12, 0.8, 0, 0.2, 1.8, "#f1f1f1"], // tail plane [0.12, 1, 0.8, 0, 0.6, 1.8, "#e63946"], // fin ]; for (const [w, h, d, x, y, z, c] of parts) body3d.add([box(w, h, d), pos(x, y, z), color(c)]); // Flight state: angles in degrees, speed in m/s, vy is the extra sink caused by lost lift. const f = (body3d.f = { speed: 0, throttle: 0, yaw: 0, pitch: 0, roll: 0, vy: 0, airborne: false, stall: false, passed: 0 }); let camYaw = 0;The rings
Each ring is a three.js torus oriented by its heading. Being close is not enough to count a pass: the function checks that the plane crosses the ring's disc, going from the side you arrive from to the other, and does so inside the radius. So a ring does not count if you graze it from behind or from outside. They are crossed in order and the crossed one turns green.
const rings = RINGS.map(([x, y, z, heading]) => { const r = (heading * Math.PI) / 180; const ring = add([mesh(new THREE.TorusGeometry(16, 1.1, 8, 32)), pos(x, y, z), rotate(0, heading, 0), color("#4cc9f0"), "ring"]); return { ring, normal: vec3(Math.sin(r), 0, Math.cos(r)) }; }); // A ring counts when the plane crosses its disc, coming from the side its normal points to. function checkRings(before) { const next = rings[f.passed]; if (!next) return; const side = (p) => p.clone().sub(next.ring.pos).dot(next.normal); const crossed = side(before) > 0 && side(body3d.pos) <= 0; if (crossed && body3d.pos.distanceTo(next.ring.pos) < 20) { next.ring.color = rgb(144, 190, 109); beep({ freq: 660, slideTo: 990, duration: 0.25, type: "triangle" }); f.passed++; } }The flight model
This is the heart of the genre and it is integrated in fixed steps of 1/60 s, so it behaves the same with few or many frames. Speed grows with the engine and falls with drag (which grows with the square of the speed) and when climbing. Lift is min(1, (speed/STALL)²): at 1 the plane climbs in proportion to its pitch; with less, the nose drops by itself and the plane sinks. Banking turns the heading by g·tan(bank)/speed. On touching the ground the game decides between landing and crash: vertical fall faster than 5 m/s, bank over 15°, nose too low or off the runway. If you flew through all rings and stop on the runway, you win.
// Simplified flight model, integrated in small fixed steps so it does not depend on the frame rate. function fly(dt) { const rad = Math.PI / 180; const input = (neg, posit) => (isButtonDown(posit) ? 1 : 0) - (isButtonDown(neg) ? 1 : 0); f.throttle = Math.min(1, Math.max(0, f.throttle + input("slower", "faster") * 0.5 * dt)); const lift = Math.min(1, (f.speed / STALL) ** 2); // wings carry the plane only if it is fast enough const turn = input("left", "right"); // Speed: engine, drag, and gravity along the climb or dive; on the ground, friction and brakes. f.speed += (f.throttle * THRUST - DRAG * f.speed ** 2 - G * 0.5 * Math.sin(f.pitch * rad)) * dt; if (!f.airborne) f.speed -= (2 + (f.throttle < 0.05 ? 8 : 0)) * dt; f.speed = Math.max(0, f.speed); // Pitch: the nose keeps its angle, but a stalled plane drops its nose. f.pitch += input("nose_up", "nose_down") * -35 * dt; if (f.airborne) f.pitch -= 30 * (1 - lift) * dt; f.pitch = Math.min(40, Math.max(f.airborne ? -40 : 0, f.pitch)); if (!f.airborne && !input("nose_up", "nose_down")) f.pitch *= 1 - 3 * dt; // Roll turns the plane: a coordinated turn changes heading by g * tan(roll) / speed. if (f.airborne) { f.roll += (turn ? turn * 80 : -f.roll * 1.5) * dt; f.roll = Math.min(60, Math.max(-60, f.roll)); f.yaw -= ((G * Math.tan(f.roll * rad)) / Math.max(f.speed, 10)) * dt / rad; } else { f.yaw -= turn * 30 * Math.min(1, f.speed / 8) * dt; // steering on the ground f.roll = 0; } // Vertical speed: the climb is proportional to lift; missing lift becomes sink. f.vy += (-G * (1 - lift) - f.vy * 2 * lift) * dt; const climb = Math.sin(f.pitch * rad) * f.speed * lift + f.vy; const before = body3d.pos.clone(); const run = f.speed * Math.cos(f.pitch * rad); body3d.pos.x += -Math.sin(f.yaw * rad) * run * dt; body3d.pos.z += -Math.cos(f.yaw * rad) * run * dt; body3d.pos.y += climb * dt; f.stall = f.airborne && lift < 1; if (body3d.pos.y > GROUND_Y + 0.3) f.airborne = true; checkRings(before); if (body3d.pos.y <= GROUND_Y) { const onRunway = Math.abs(body3d.pos.x) < RUNWAY.halfWidth && body3d.pos.z < RUNWAY.from && body3d.pos.z > RUNWAY.to; const hard = f.airborne && (climb < -5 || Math.abs(f.roll) > 15 || f.pitch < -10); if (hard || !onRunway) return "crash"; body3d.pos.y = GROUND_Y; f.airborne = false; f.vy = 0; if (f.passed === rings.length && f.speed < 1.5) return "landed"; } }Instruments and stall warning
The counter shows speed, altitude and throttle, and on the right the rings with an arrow towards the next one and its distance: the arrow comes from comparing the plane's heading with the direction to the ring. The stall warning blinks while lift is below 1, exactly when the player needs to know to lower the nose and gain speed.
const hud = add([text("", { size: 16, font: FONT }), pos(14, 10), fixed()]); const hint = add([text("", { size: 18, font: FONT }), pos(626, 10), anchor("topright"), fixed()]); const warning = add([text(t({ es: "¡PÉRDIDA! Baja el morro", en: "STALL! Lower the nose" }), { size: 26, font: FONT }), pos(320, 90), anchor("center"), color("#e63946"), fixed()]); function updateHud() { const alt = Math.max(0, Math.round(body3d.pos.y - GROUND_Y)); hud.text = `${t({ es: "Velocidad", en: "Speed" })} ${Math.round(f.speed * 3.6)} km/h\n${t({ es: "Altitud", en: "Altitude" })} ${alt} m\n${t({ es: "Motor", en: "Throttle" })} ${Math.round(f.throttle * 100)}%`; const next = rings[f.passed]; if (next) { // Which way is the next ring? Compare it with the plane's heading. const to = next.ring.pos.clone().sub(body3d.pos); let diff = (Math.atan2(-to.x, -to.z) * 180) / Math.PI - f.yaw; diff = ((((diff + 180) % 360) + 360) % 360) - 180; const arrow = Math.abs(diff) < 12 ? "▲" : diff > 0 ? "◀" : "▶"; hint.text = `◯ ${f.passed} / ${rings.length} ${arrow} ${Math.round(to.length())} m`; } else hint.text = t({ es: `◯ ${f.passed} / ${rings.length} ¡Aterriza en la pista!`, en: `◯ ${f.passed} / ${rings.length} Land on the runway!` }); warning.hidden = !f.stall || Math.floor(time() * 4) % 2 === 0; }The chase camera
No camera controller: every frame it is placed with camPos() behind the plane and aimed with camLookAt(). The camera heading follows the plane's with a delay, so when turning you see the plane from the side and better understand where it turns. The camera does not copy the roll: the horizon always stays level.
// Chase camera: it follows the heading with a delay, so turns are easy to read. function followPlane(dt) { const rad = Math.PI / 180; camYaw += ((((f.yaw - camYaw + 180) % 360) + 360) % 360 - 180) * Math.min(1, 3 * dt); const back = vec3(Math.sin(camYaw * rad), 0, Math.cos(camYaw * rad)).multiplyScalar(13); camPos(body3d.pos.x + back.x, Math.max(1.5, body3d.pos.y + 4 - f.pitch * 0.1), body3d.pos.z + back.z); camLookAt(body3d.pos.clone().add(vec3(-back.x, 0, -back.z).multiplyScalar(0.6))); }Scenes
Three scenes (title, game and end) and go() to move between them. The title screen reuses the world with a camera that orbits on its own; the ending tells a landing from a crash and gives a hint on what to correct.
scene("title", () => { add([text("Flight simulator", { size: 40, font: FONT }), pos(320, 110), anchor("center"), fixed()]); add([text(t({ es: "Despega, cruza los anillos y aterriza en la pista", en: "Take off, fly through the rings and land on the runway" }), { size: 16, font: FONT }), pos(320, 170), anchor("center"), fixed()]); add([text(t({ es: "Motor al máximo (E), acelera y tira hacia ti (↓) para despegar", en: "Full throttle (E), speed up and pull back (↓) to take off" }), { size: 14, font: FONT }), pos(320, 205), anchor("center"), fixed()]); add([text(t({ es: "Espacio para empezar", en: "Space to start" }), { size: 16, font: FONT }), pos(320, 250), anchor("center"), fixed()]); buildWorld(); const orbit = orbitCamera({ target: vec3(0, 5, -60), distance: 90, maxDistance: 200, autoRotate: 10, interactive: false }); orbit.pitch = 15; onButtonPress("start", () => go("game")); }); scene("end", ({ ok, rings, time }) => { const title = ok ? { es: "¡Aterrizaje perfecto!", en: "Perfect landing!" } : { es: "Te estrellaste", en: "You crashed" }; const tip = ok ? { es: `Anillos: ${rings}. Tiempo: ${Math.round(time)} s`, en: `Rings: ${rings}. Time: ${Math.round(time)} s` } : { es: "Toca el suelo despacio, nivelado y sobre la pista", en: "Touch down slowly, level, and on the runway" }; add([text(t(title), { size: 36, font: FONT }), pos(320, 140), anchor("center"), fixed()]); add([text(t(tip), { size: 16, font: FONT }), pos(320, 190), anchor("center"), fixed()]); add([text(t({ es: "Espacio para volver a volar", en: "Space to fly again" }), { size: 16, font: FONT }), pos(320, 240), anchor("center"), fixed()]); onButtonPress("start", () => go("game")); }); go("title");
What we simplified
- There are no separate rudder or ailerons and no turning inertia. The turn is a simplified coordinated turn (heading changes with g·tan(bank)/speed), the bank levels out by itself when you release the keys and the nose keeps its angle.
- Lift is just a number between 0 and 1 that depends on speed. There is no angle of attack, flaps, wind, fuel or real instruments.
- The terrain is flat; the trees and far hills are decoration without collision. Only the ground counts as an obstacle, and touching it off the runway is also a crash.
- The plane is a handful of boxes and the sound is synthesized beeps. There is no combat, weather or other aircraft.
To modify it
- Make the plane level itself (pitch towards 0) when you release the keys, and compare how it feels with the original.
- Add flaps on a key that lower STALL at the cost of more drag, so you can land more slowly.
- Add a mountain with collision and a ground-proximity warning that sounds when altitude is low and the nose points down.
Full code
import threeplay from "../../vendor/threeplay/threeplay.mjs";
import { FONT, t, touchControls } from "../common.js";
// #region setup
const k = threeplay({
width: 640,
height: 360,
letterbox: true,
background: "#9ad1f0",
buttons: {
left: { keyboard: ["left", "a"] },
right: { keyboard: ["right", "d"] },
nose_down: { keyboard: ["up", "w"] },
nose_up: { keyboard: ["down", "s"] },
faster: { keyboard: ["e", "shift"] },
slower: { keyboard: ["q", "ctrl"] },
start: { keyboard: ["space", "enter"] },
},
});
touchControls(k, [
{ button: "left", label: "◀" },
{ button: "nose_down", label: "▲" },
{ button: "nose_up", label: "▼" },
{ button: "right", label: "▶" },
{ button: "faster", label: "+", side: "right" },
{ button: "slower", label: "−", side: "right" },
]);
const G = 9.8;
const THRUST = 8; // acceleration at full throttle
const DRAG = 0.005; // drag grows with speed squared: top speed = sqrt(THRUST / DRAG)
const STALL = 20; // below this speed the wings do not carry the plane
const GROUND_Y = 0.9; // height of the plane's center when the wheels touch the ground
const RUNWAY = { halfWidth: 8, from: 40, to: -200 }; // z range; the runway lies along z
const STEP = 1 / 60;
// #endregion
// #region world
// [x, altitude, z, heading in degrees]: the course is a loop that ends in a final approach.
const RINGS = [
[0, 18, -210, 0],
[0, 32, -340, 0],
[-180, 45, -420, 90],
[-300, 45, -150, 180],
[-90, 35, 250, 270],
[0, 22, 130, 0],
];
function buildWorld() {
setFog({ color: "#9ad1f0", near: 150, far: 900 });
add([plane(6000, 6000), pos(0, 0, 0), color("#7bb661")]);
const length = RUNWAY.from - RUNWAY.to;
add([box(RUNWAY.halfWidth * 2, 0.1, length), pos(0, 0.05, (RUNWAY.from + RUNWAY.to) / 2), color("#4a4e57")]);
for (let z = RUNWAY.from - 10; z > RUNWAY.to; z -= 20) add([box(0.6, 0.12, 8), pos(0, 0.1, z), color("#f1f1f1")]);
// Trees and far hills are decoration: they give a sense of speed and depth. A fixed seed keeps the map the same.
let seed = 7;
const random = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
for (let i = 0; i < 160; i++) {
const x = (random() - 0.5) * 1400 - 150;
const z = (random() - 0.5) * 1400 - 100;
if (Math.abs(x) < 25 && z < RUNWAY.from + 20 && z > RUNWAY.to - 20) continue;
add([cone(3 + random() * 3, 10 + random() * 8), pos(x, 6, z), color("#2d6a4f")]);
}
for (let i = 0; i < 12; i++) {
const a = (i / 12) * Math.PI * 2;
add([cone(120, 90 + (i % 3) * 40), pos(Math.cos(a) * 1100 - 150, 60, Math.sin(a) * 1100 - 100), color("#8d99ae")]);
}
}
// #endregion
scene("game", () => {
buildWorld();
// #region plane
// A plane is a few boxes. Nose points to -Z; rotation is yaw, then pitch, then roll.
const body3d = add([pos(0, GROUND_Y, 30), rotate(), "plane"]);
body3d.rotOrder = "YXZ"; // rot reads as heading (y), pitch (x) and roll (z)
const parts = [
[0.8, 0.8, 4, 0, 0, 0, "#e63946"], // fuselage
[7, 0.15, 1.2, 0, 0.1, -0.2, "#f1f1f1"], // wings
[2.2, 0.12, 0.8, 0, 0.2, 1.8, "#f1f1f1"], // tail plane
[0.12, 1, 0.8, 0, 0.6, 1.8, "#e63946"], // fin
];
for (const [w, h, d, x, y, z, c] of parts) body3d.add([box(w, h, d), pos(x, y, z), color(c)]);
// Flight state: angles in degrees, speed in m/s, vy is the extra sink caused by lost lift.
const f = (body3d.f = { speed: 0, throttle: 0, yaw: 0, pitch: 0, roll: 0, vy: 0, airborne: false, stall: false, passed: 0 });
let camYaw = 0;
// #endregion
// #region rings
const rings = RINGS.map(([x, y, z, heading]) => {
const r = (heading * Math.PI) / 180;
const ring = add([mesh(new THREE.TorusGeometry(16, 1.1, 8, 32)), pos(x, y, z), rotate(0, heading, 0), color("#4cc9f0"), "ring"]);
return { ring, normal: vec3(Math.sin(r), 0, Math.cos(r)) };
});
// A ring counts when the plane crosses its disc, coming from the side its normal points to.
function checkRings(before) {
const next = rings[f.passed];
if (!next) return;
const side = (p) => p.clone().sub(next.ring.pos).dot(next.normal);
const crossed = side(before) > 0 && side(body3d.pos) <= 0;
if (crossed && body3d.pos.distanceTo(next.ring.pos) < 20) {
next.ring.color = rgb(144, 190, 109);
beep({ freq: 660, slideTo: 990, duration: 0.25, type: "triangle" });
f.passed++;
}
}
// #endregion
// #region flight
// Simplified flight model, integrated in small fixed steps so it does not depend on the frame rate.
function fly(dt) {
const rad = Math.PI / 180;
const input = (neg, posit) => (isButtonDown(posit) ? 1 : 0) - (isButtonDown(neg) ? 1 : 0);
f.throttle = Math.min(1, Math.max(0, f.throttle + input("slower", "faster") * 0.5 * dt));
const lift = Math.min(1, (f.speed / STALL) ** 2); // wings carry the plane only if it is fast enough
const turn = input("left", "right");
// Speed: engine, drag, and gravity along the climb or dive; on the ground, friction and brakes.
f.speed += (f.throttle * THRUST - DRAG * f.speed ** 2 - G * 0.5 * Math.sin(f.pitch * rad)) * dt;
if (!f.airborne) f.speed -= (2 + (f.throttle < 0.05 ? 8 : 0)) * dt;
f.speed = Math.max(0, f.speed);
// Pitch: the nose keeps its angle, but a stalled plane drops its nose.
f.pitch += input("nose_up", "nose_down") * -35 * dt;
if (f.airborne) f.pitch -= 30 * (1 - lift) * dt;
f.pitch = Math.min(40, Math.max(f.airborne ? -40 : 0, f.pitch));
if (!f.airborne && !input("nose_up", "nose_down")) f.pitch *= 1 - 3 * dt;
// Roll turns the plane: a coordinated turn changes heading by g * tan(roll) / speed.
if (f.airborne) {
f.roll += (turn ? turn * 80 : -f.roll * 1.5) * dt;
f.roll = Math.min(60, Math.max(-60, f.roll));
f.yaw -= ((G * Math.tan(f.roll * rad)) / Math.max(f.speed, 10)) * dt / rad;
} else {
f.yaw -= turn * 30 * Math.min(1, f.speed / 8) * dt; // steering on the ground
f.roll = 0;
}
// Vertical speed: the climb is proportional to lift; missing lift becomes sink.
f.vy += (-G * (1 - lift) - f.vy * 2 * lift) * dt;
const climb = Math.sin(f.pitch * rad) * f.speed * lift + f.vy;
const before = body3d.pos.clone();
const run = f.speed * Math.cos(f.pitch * rad);
body3d.pos.x += -Math.sin(f.yaw * rad) * run * dt;
body3d.pos.z += -Math.cos(f.yaw * rad) * run * dt;
body3d.pos.y += climb * dt;
f.stall = f.airborne && lift < 1;
if (body3d.pos.y > GROUND_Y + 0.3) f.airborne = true;
checkRings(before);
if (body3d.pos.y <= GROUND_Y) {
const onRunway = Math.abs(body3d.pos.x) < RUNWAY.halfWidth && body3d.pos.z < RUNWAY.from && body3d.pos.z > RUNWAY.to;
const hard = f.airborne && (climb < -5 || Math.abs(f.roll) > 15 || f.pitch < -10);
if (hard || !onRunway) return "crash";
body3d.pos.y = GROUND_Y;
f.airborne = false;
f.vy = 0;
if (f.passed === rings.length && f.speed < 1.5) return "landed";
}
}
// #endregion
// #region hud
const hud = add([text("", { size: 16, font: FONT }), pos(14, 10), fixed()]);
const hint = add([text("", { size: 18, font: FONT }), pos(626, 10), anchor("topright"), fixed()]);
const warning = add([text(t({ es: "¡PÉRDIDA! Baja el morro", en: "STALL! Lower the nose" }), { size: 26, font: FONT }), pos(320, 90), anchor("center"), color("#e63946"), fixed()]);
function updateHud() {
const alt = Math.max(0, Math.round(body3d.pos.y - GROUND_Y));
hud.text = `${t({ es: "Velocidad", en: "Speed" })} ${Math.round(f.speed * 3.6)} km/h\n${t({ es: "Altitud", en: "Altitude" })} ${alt} m\n${t({ es: "Motor", en: "Throttle" })} ${Math.round(f.throttle * 100)}%`;
const next = rings[f.passed];
if (next) {
// Which way is the next ring? Compare it with the plane's heading.
const to = next.ring.pos.clone().sub(body3d.pos);
let diff = (Math.atan2(-to.x, -to.z) * 180) / Math.PI - f.yaw;
diff = ((((diff + 180) % 360) + 360) % 360) - 180;
const arrow = Math.abs(diff) < 12 ? "▲" : diff > 0 ? "◀" : "▶";
hint.text = `◯ ${f.passed} / ${rings.length} ${arrow} ${Math.round(to.length())} m`;
} else hint.text = t({ es: `◯ ${f.passed} / ${rings.length} ¡Aterriza en la pista!`, en: `◯ ${f.passed} / ${rings.length} Land on the runway!` });
warning.hidden = !f.stall || Math.floor(time() * 4) % 2 === 0;
}
// #endregion
// #region camera
// Chase camera: it follows the heading with a delay, so turns are easy to read.
function followPlane(dt) {
const rad = Math.PI / 180;
camYaw += ((((f.yaw - camYaw + 180) % 360) + 360) % 360 - 180) * Math.min(1, 3 * dt);
const back = vec3(Math.sin(camYaw * rad), 0, Math.cos(camYaw * rad)).multiplyScalar(13);
camPos(body3d.pos.x + back.x, Math.max(1.5, body3d.pos.y + 4 - f.pitch * 0.1), body3d.pos.z + back.z);
camLookAt(body3d.pos.clone().add(vec3(-back.x, 0, -back.z).multiplyScalar(0.6)));
}
// #endregion
let result = null;
onUpdate(() => {
for (let left = dt(); left > 0 && !result; left -= STEP) result = fly(Math.min(STEP, left));
body3d.rot.set(f.pitch, f.yaw, -f.roll);
followPlane(dt());
updateHud();
if (result) {
const outcome = result;
beep({ freq: outcome === "crash" ? 120 : 523, slideTo: outcome === "crash" ? 40 : 1046, duration: 0.6, type: outcome === "crash" ? "sawtooth" : "triangle" });
go("end", { ok: outcome === "landed", rings: f.passed, time: time() });
}
});
});
// #region scenes
scene("title", () => {
add([text("Flight simulator", { size: 40, font: FONT }), pos(320, 110), anchor("center"), fixed()]);
add([text(t({ es: "Despega, cruza los anillos y aterriza en la pista", en: "Take off, fly through the rings and land on the runway" }), { size: 16, font: FONT }), pos(320, 170), anchor("center"), fixed()]);
add([text(t({ es: "Motor al máximo (E), acelera y tira hacia ti (↓) para despegar", en: "Full throttle (E), speed up and pull back (↓) to take off" }), { size: 14, font: FONT }), pos(320, 205), anchor("center"), fixed()]);
add([text(t({ es: "Espacio para empezar", en: "Space to start" }), { size: 16, font: FONT }), pos(320, 250), anchor("center"), fixed()]);
buildWorld();
const orbit = orbitCamera({ target: vec3(0, 5, -60), distance: 90, maxDistance: 200, autoRotate: 10, interactive: false });
orbit.pitch = 15;
onButtonPress("start", () => go("game"));
});
scene("end", ({ ok, rings, time }) => {
const title = ok ? { es: "¡Aterrizaje perfecto!", en: "Perfect landing!" } : { es: "Te estrellaste", en: "You crashed" };
const tip = ok
? { es: `Anillos: ${rings}. Tiempo: ${Math.round(time)} s`, en: `Rings: ${rings}. Time: ${Math.round(time)} s` }
: { es: "Toca el suelo despacio, nivelado y sobre la pista", en: "Touch down slowly, level, and on the runway" };
add([text(t(title), { size: 36, font: FONT }), pos(320, 140), anchor("center"), fixed()]);
add([text(t(tip), { size: 16, font: FONT }), pos(320, 190), anchor("center"), fixed()]);
add([text(t({ es: "Espacio para volver a volar", en: "Space to fly again" }), { size: 16, font: FONT }), pos(320, 240), anchor("center"), fixed()]);
onButtonPress("start", () => go("game"));
});
go("title");
// #endregionHistory
- 1975Origin
Taito's Interceptor (1975) was a first-person arcade combat flight simulator. Sega's Jet Rocket (1970) already simulated flight, but it was an electro-mechanical machine, not a video game.
Flight simulation video game (Wikipedia) - 1982
Microsoft licenses Sublogic's Flight Simulator for the IBM PC, giving rise to Microsoft Flight Simulator.
Microsoft Flight Simulator (Wikipedia)
Reference games
1982
Microsoft Flight Simulator
Microsoft's first flight simulator, based on subLOGIC's work. You fly a light aircraft with realistic instruments over a world drawn with very simple lines.
Subgenres
- Space flight simulatorYou fly a spacecraft from the cockpit: manoeuvring, docking, trading or fighting between planets and stations. Depending on the game, the challenge is mastering realistic orbital physics or surviving and thriving in an open galaxy.