
Simulador de vuelo
Pilotas un avión u otra aeronave con controles que imitan los reales: despegas, navegas y aterrizas atendiendo a los instrumentos, al clima y a la física del vuelo. Va desde la simulación muy realista hasta el combate aéreo de estilo arcade.
También se llama: simulación de vuelo
Esta es una ficha básica: tiene la definición y la clasificación. Las fichas completas suman historia, juegos y una demo.
Demo propia
Controles. Flechas o WASD: izquierda y derecha alabean (inclinan el avión para girar); abajo o S levanta el morro y arriba o W lo baja. E o Mayús aumentan el motor y Q o Ctrl lo reducen. Espacio para empezar. En móvil, los botones en pantalla: ◀ ▶ alabeo, ▲ ▼ morro, + − motor.
Abrir en pantalla completaUn avión sencillo en 3D con un modelo de vuelo honesto: el motor da velocidad, el alabeo hace girar y las alas solo sostienen el avión si va lo bastante rápido. Despegas de una pista, cruzas una serie de anillos y vuelves a aterrizar sin estrellarte. Está hecha con threeplay, un motor 3D en la línea de Kaplay.
Hecha con threeplay, en unas 186 líneas de JavaScript.
Cómo está hecha
Configuración y constantes de vuelo
Se crea el juego a 640×360, se definen los botones virtuales (los del móvil pulsan los mismos) y las constantes que dan carácter al avión. THRUST y DRAG fijan la velocidad máxima, STALL es la velocidad bajo la cual las alas dejan de sostener, y las medidas de la pista se usan al aterrizar. Cambiar STALL o THRUST convierte el avión en un planeador torpe o en un caza nervioso.
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;El mundo y el recorrido
RINGS es la lista del recorrido: posición, altitud y rumbo de cada anillo. Está pensado como un circuito que termina en una aproximación a la pista, lo que enseña a planificar el viraje. El suelo es un plano, la pista una caja con rayas, y los árboles y colinas, conos puestos con un generador de números con semilla fija para que el mapa sea siempre igual. setFog() esconde el horizonte y da profundidad.
// [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")]); } }El avión y su estado
El avión es un objeto vacío con cuatro cajas hijas (fuselaje, alas, cola y aleta). Su estado de vuelo vive en un objeto f: velocidad, motor, rumbo, cabeceo, alabeo y vy, la caída extra por falta de sustentación. No usa body() ni Rapier: la física es propia porque un modelo de vuelo es una fórmula, no una colisión de cuerpos. Con rotate() y rotOrder = «YXZ», rot aplica primero el rumbo, luego el cabeceo y luego el alabeo, como en un avión de verdad.
// 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;Los anillos
Cada anillo es un toroide de three.js orientado según su rumbo. Para contar un paso no basta estar cerca: la función comprueba que el avión cruza el disco del anillo, es decir, que pasa del lado desde el que se llega al otro, y que lo hace dentro del radio. Así un anillo no cuenta si lo rozas por detrás o por fuera. Se cruzan en orden y el cruzado se pone verde.
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++; } }El modelo de vuelo
Es el corazón del género y se integra en pasos fijos de 1/60 s, así que se comporta igual con pocos o muchos fotogramas. La velocidad sube con el motor y baja con la resistencia (que crece con el cuadrado de la velocidad) y al subir. La sustentación es min(1, (velocidad/STALL)²): con 1 el avión sube en proporción al cabeceo; con menos, el morro cae solo y el avión se hunde. El alabeo gira el rumbo con g·tan(alabeo)/velocidad. Al tocar el suelo se decide si es aterrizaje o choque: caída vertical mayor de 5 m/s, alabeo mayor de 15°, morro muy bajo o fuera de la pista. Si cruzaste todos los anillos y paras en la pista, ganas.
// 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"; } }Instrumentos y aviso de pérdida
El marcador muestra velocidad, altitud y motor, y a la derecha los anillos con una flecha hacia el siguiente y su distancia: la flecha sale de comparar el rumbo del avión con la dirección al anillo. El aviso de pérdida parpadea mientras la sustentación sea menor que 1, justo cuando el jugador necesita saber que debe bajar el morro y ganar velocidad.
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; }La cámara de persecución
Sin controlador de cámara: cada fotograma se coloca con camPos() detrás del avión y se apunta con camLookAt(). El rumbo de la cámara sigue al del avión con retraso, así que al virar ves el avión de lado y entiendes mejor hacia dónde gira. La cámara no copia el alabeo: el horizonte siempre queda recto.
// 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))); }Escenas
Tres escenas (title, game y end) y go() para pasar de una a otra. La pantalla de título reutiliza el mundo con una cámara que orbita sola; el final distingue aterrizaje de choque y da una pista de qué corregir.
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");
Qué simplificamos
- No hay timón ni alerones por separado ni inercia de giro. El giro es un viraje coordinado simplificado (el rumbo cambia según g·tan(alabeo)/velocidad), el alabeo vuelve solo a nivel cuando sueltas las teclas y el morro mantiene su ángulo.
- La sustentación es solo un número entre 0 y 1 que depende de la velocidad. No hay ángulo de ataque, flaps, viento, combustible ni instrumentos reales.
- El terreno es plano; los árboles y las colinas lejanas son decoración sin colisión. Solo el suelo cuenta como obstáculo, y tocarlo fuera de la pista también es un choque.
- El avión es un puñado de cajas y el sonido son pitidos sintetizados. No hay combate, clima ni otras aeronaves.
Para modificarla
- Haz que el avión se nivele solo (cabeceo hacia 0) cuando sueltas las teclas, y compara cómo se siente con el original.
- Agrega flaps con una tecla que baje STALL a cambio de más resistencia, para poder aterrizar más despacio.
- Agrega una montaña con colisión y un aviso de proximidad al suelo que suene cuando la altitud sea baja y el morro apunte hacia abajo.
Código completo
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");
// #endregionHistoria
- 1975Origen
Interceptor (1975), de Taito, era un simulador de combate aéreo en primera persona para salones recreativos. Jet Rocket (1970), de Sega, ya simulaba el vuelo, pero era una máquina electromecánica, no un videojuego.
Flight simulation video game (Wikipedia) - 1982
Microsoft licencia el Flight Simulator de Sublogic para IBM PC: nace Microsoft Flight Simulator.
Microsoft Flight Simulator (Wikipedia)
Juegos de referencia
1982
Microsoft Flight Simulator
El primer simulador de vuelo de Microsoft, basado en el trabajo de subLOGIC. Pilotas una avioneta con instrumentos realistas sobre un mundo de líneas muy simples.
Subgéneros
- Simulador espacialPilotas una nave en el espacio desde la cabina: maniobras, atracas, comercias o combates entre planetas y estaciones. Según el juego, el reto es dominar una física orbital realista o sobrevivir y prosperar en una galaxia abierta.