Prompt specification
Build or customize the Three.js 3D scene "Plan a Route Across Gravity Frames" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Plan a Route Across Gravity Frames
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/plan-a-route-across-gravity-frames-x3456
Scene Description Prompt:
Use Three.js from cdnjs to create a playable puzzle requiring a fixed sequence of gravity changes and safe landings. Validate actual collision paths and distinguish fictional controls from real gravitational technology. Deliver one self-contained HTML file with low-poly forms.
Working Three.js Starter (plan-a-route-across-gravity-frames-x3456):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<title>Gravity Relay — Collision Puzzle</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 22, 39, 0.82);
--panel-strong: rgba(8, 18, 33, 0.95);
--line: rgba(157, 196, 255, 0.18);
--text: #e9f3ff;
--muted: #91a6c2;
--cyan: #67d9ff;
--green: #78f7b0;
--amber: #ffd479;
--red: #ff6b7d;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 38%, #152945 0, #081426 48%, #040914 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
user-select: none;
}
button,
summary {
-webkit-tap-highlight-color: transparent;
}
button {
color: var(--text);
font: inherit;
}
#viewport,
#viewport canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
}
#viewport canvas {
display: block;
}
.hud {
position: absolute;
z-index: 5;
pointer-events: none;
}
.panel {
border: 1px solid var(--line);
border-radius: 14px;
background: var(--panel);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(13px);
-webkit-backdrop-filter: blur(13px);
}
#titlePanel {
top: 18px;
left: 18px;
padding: 14px 17px 13px;
min-width: 285px;
}
.eyebrow {
margin-bottom: 5px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(21px, 2.2vw, 31px);
line-height: 1;
letter-spacing: 0.055em;
}
#stageTitle {
margin-top: 8px;
color: var(--muted);
font: 700 11px/1.3 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
letter-spacing: 0.08em;
}
#status {
position: absolute;
top: 130px;
left: 18px;
max-width: min(520px, calc(100vw - 36px));
padding: 10px 13px;
border-left: 3px solid var(--cyan);
border-radius: 6px;
background: rgba(5, 14, 28, 0.75);
color: #c7daf2;
font-size: 12px;
line-height: 1.45;
transition: border-color 160ms ease, color 160ms ease;
}
#sciencePanel {
top: 18px;
right: 18px;
width: min(350px, calc(100vw - 36px));
padding: 11px 13px;
pointer-events: auto;
}
#sciencePanel summary {
color: var(--amber);
cursor: pointer;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.07em;
list-style: none;
}
#sciencePanel summary::-webkit-details-marker {
display: none;
}
#sciencePanel summary::before {
content: "◆";
margin-right: 8px;
color: var(--amber);
}
#sciencePanel p {
margin: 10px 0 1px;
color: #b7c8dc;
font-size: 11px;
line-height: 1.5;
}
#sciencePanel strong {
color: #f0e5c9;
}
#sequencePanel {
left: 18px;
bottom: 91px;
padding: 12px;
}
.panel-label {
margin-bottom: 9px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
#sequence {
display: flex;
gap: 6px;
}
.seq-chip {
display: grid;
grid-template-columns: 27px 1fr;
align-items: center;
gap: 6px;
min-width: 82px;
padding: 8px 9px;
border: 1px solid rgba(150, 185, 230, 0.15);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
opacity: 0.45;
transition: 160ms ease;
}
.seq-chip b {
display: grid;
width: 27px;
height: 27px;
place-items: center;
border-radius: 7px;
background: rgba(255, 255, 255, 0.06);
color: var(--text);
font: 800 12px ui-monospace, monospace;
}
.seq-chip span {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
}
.seq-chip.active {
border-color: rgba(103, 217, 255, 0.65);
background: rgba(103, 217, 255, 0.08);
opacity: 1;
box-shadow: 0 0 20px rgba(103, 217, 255, 0.08);
}
.seq-chip.active b {
background: var(--cyan);
color: #05111f;
}
.seq-chip.complete {
border-color: rgba(120, 247, 176, 0.45);
opacity: 0.9;
}
.seq-chip.complete b {
background: rgba(120, 247, 176, 0.2);
color: var(--green);
}
#telemetry {
right: 18px;
bottom: 91px;
width: 252px;
padding: 12px 14px;
}
.tele-row {
display: flex;
justify-content: space-between;
gap: 16px;
padding: 5px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.055);
color: var(--muted);
font-size: 10px;
letter-spacing: 0.07em;
}
.tele-row:last-child {
border-bottom: 0;
}
.tele-row b {
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-weight: 700;
letter-spacing: 0;
text-align: right;
}
#validationValue {
color: var(--green);
}
#collisionMode {
margin-top: 8px;
color: #7189a7;
font-size: 8px;
letter-spacing: 0.08em;
text-align: center;
}
#controlPanel {
left: 50%;
bottom: 17px;
display: flex;
align-items: center;
gap: 13px;
max-width: calc(100vw - 36px);
padding: 9px 11px;
transform: translateX(-50%);
pointer-events: auto;
}
.control-help {
padding: 0 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.45;
white-space: nowrap;
}
.control-help strong {
color: var(--text);
}
kbd {
display: inline-grid;
min-width: 22px;
height: 22px;
margin: 0 1px;
padding: 0 5px;
place-items: center;
border: 1px solid rgba(255, 255, 255, 0.16);
border-bottom-width: 3px;
border-radius: 5px;
background: rgba(255, 255, 255, 0.06);
color: #dcecff;
font: 700 10px ui-monospace, monospace;
}
#relayButtons {
display: flex;
gap: 5px;
}
.relay-button {
min-width: 48px;
padding: 7px 7px 6px;
border: 1px solid rgba(151, 184, 225, 0.2);
border-radius: 8px;
background: rgba(255, 255, 255, 0.045);
color: var(--muted);
cursor: pointer;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.06em;
transition: 150ms ease;
}
.relay-button b {
display: block;
margin-bottom: 1px;
color: var(--text);
font: 900 14px ui-monospace, monospace;
}
.relay-button:hover,
.relay-button.expected {
border-color: rgba(103, 217, 255, 0.7);
background: rgba(103, 217, 255, 0.1);
color: #bdefff;
}
.relay-button.expected b {
color: var(--cyan);
}
.small-button {
padding: 9px 11px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 8px;
background: rgba(255, 255, 255, 0.045);
color: var(--muted);
cursor: pointer;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
}
.small-button:hover {
border-color: rgba(103, 217, 255, 0.45);
color: var(--text);
}
#touchControls {
position: absolute;
z-index: 8;
bottom: 15px;
left: 15px;
display: none;
grid-template-columns: repeat(3, 46px);
grid-template-rows: repeat(3, 46px);
gap: 4px;
pointer-events: auto;
}
#touchControls button {
border: 1px solid rgba(151, 184, 225, 0.25);
border-radius: 12px;
background: rgba(10, 22, 39, 0.82);
color: #d9edff;
font-size: 20px;
touch-action: none;
}
#touchControls button:active {
background: rgba(103, 217, 255, 0.24);
}
#touchControls .up {
grid-column: 2;
grid-row: 1;
}
#touchControls .left {
grid-column: 1;
grid-row: 2;
}
#touchControls .down {
grid-column: 2;
grid-row: 3;
}
#touchControls .right {
grid-column: 3;
grid-row: 2;
}
#overlay {
position: absolute;
z-index: 20;
inset: 0;
display: grid;
padding: 24px;
place-items: center;
background: rgba(2, 7, 15, 0.67);
backdrop-filter: blur(8px);
-webkit-backdrop-filter: blur(8px);
transition: opacity 180ms ease;
}
#overlay.hidden {
display: none;
}
.briefing {
width: min(620px, 100%);
max-height: calc(100vh - 48px);
overflow: auto;
padding: clamp(22px, 4vw, 38px);
border: 1px solid rgba(153, 196, 255, 0.22);
border-radius: 22px;
background:
linear-gradient(145deg, rgba(17, 36, 62, 0.97), rgba(7, 16, 31, 0.98));
box-shadow: 0 30px 100px rgba(0, 0, 0, 0.55);
}
.briefing h2 {
margin: 7px 0 12px;
font-size: clamp(34px, 6vw, 58px);
line-height: 0.95;
letter-spacing: 0.035em;
}
.briefing > p {
margin: 0 0 17px;
color: #b9cbe0;
font-size: 14px;
line-height: 1.6;
}
.brief-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 9px;
margin: 18px 0;
}
.brief-item {
padding: 13px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 11px;
background: rgba(255, 255, 255, 0.035);
}
.brief-item b {
display: block;
margin-bottom: 5px;
color: var(--cyan);
font-size: 11px;
letter-spacing: 0.08em;
}
.brief-item span {
color: #9fb4cd;
font-size: 11px;
line-height: 1.45;
}
.truth-note {
padding: 13px 14px;
border-left: 3px solid var(--amber);
border-radius: 6px;
background: rgba(255, 212, 121, 0.065);
color: #d9d4c4;
font-size: 12px;
line-height: 1.55;
}
.truth-note strong {
color: var(--amber);
}
.overlay-actions {
display: flex;
flex-wrap: wrap;
gap: 9px;
margin-top: 21px;
}
.primary-button,
.secondary-button {
min-height: 45px;
padding: 12px 19px;
border-radius: 10px;
cursor: pointer;
font-size: 11px;
font-weight: 900;
letter-spacing: 0.1em;
}
.primary-button {
border: 0;
background: var(--cyan);
color: #04101d;
box-shadow: 0 8px 25px rgba(103, 217, 255, 0.2);
}
.primary-button:hover {
background: #a1e9ff;
}
.secondary-button {
border: 1px solid rgba(255, 255, 255, 0.14);
background: rgba(255, 255, 255, 0.045);
color: #c9d9eb;
}
@media (max-width: 760px) {
#titlePanel {
top: 10px;
left: 10px;
min-width: 0;
padding: 10px 12px;
}
#sciencePanel {
top: 10px;
right: 10px;
width: 48%;
padding: 9px 10px;
}
#sciencePanel p {
font-size: 10px;
}
#status {
top: 91px;
left: 10px;
max-width: calc(100vw - 20px);
font-size: 11px;
}
#sequencePanel {
top: 153px;
right: 10px;
bottom: auto;
left: 10px;
padding: 8px;
}
#sequence {
gap: 4px;
}
.seq-chip {
grid-template-columns: 23px 1fr;
min-width: 0;
flex: 1;
gap: 4px;
padding: 6px;
}
.seq-chip b {
width: 23px;
height: 23px;
}
.seq-chip span {
font-size: 8px;
}
#telemetry {
top: 219px;
right: 10px;
bottom: auto;
width: 205px;
padding: 8px 11px;
}
.tele-row {
padding: 3px 0;
font-size: 9px;
}
#collisionMode {
display: none;
}
#controlPanel {
right: 10px;
bottom: 12px;
left: auto;
gap: 5px;
padding: 6px;
transform: none;
}
.control-help {
display: none;
}
.relay-button {
min-width: 42px;
padding: 6px 5px 5px;
}
}
@media (pointer: coarse) {
#touchControls {
display: grid;
}
#controlPanel {
left: auto;
right: 10px;
bottom: 12px;
transform: none;
}
#sequencePanel {
bottom: auto;
top: 153px;
}
#telemetry {
bottom: auto;
top: 219px;
}
}
@media (max-width: 520px) {
h1 {
font-size: 20px;
}
.eyebrow {
font-size: 8px;
}
#stageTitle {
margin-top: 5px;
font-size: 9px;
}
#sciencePanel {
width: 49%;
}
#sciencePanel summary {
font-size: 9px;
line-height: 1.35;
}
.brief-grid {
grid-template-columns: 1fr;
}
.briefing {
padding: 23px;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<header id="titlePanel" class="hud panel">
<div class="eyebrow">Swept-Collision Flight Puzzle</div>
<h1>GRAVITY RELAY</h1>
<div id="stageTitle">RELAY 1 / 4 · SEED</div>
</header>
<div id="status" class="hud" role="status" aria-live="polite">
Arm the scripted relay to begin.
</div>
<details id="sciencePanel" class="hud panel">
<summary>FICTION: scripted gravity relay</summary>
<p>
<strong>This is a fictional game mechanism.</strong> No verified portable
antigravity or handheld device can aim gravity like a compass. The arrow-key
thrusters represent conventional reaction-control propulsion; the gravity
vectors are a scripted simulation.
</p>
</details>
<section id="sequencePanel" class="hud panel">
<div class="panel-label">Locked Relay Order</div>
<div id="sequence"></div>
</section>
<section id="telemetry" class="hud panel">
<div class="tele-row"><span>GRAVITY</span><b id="gravityValue">PENDING 1</b></div>
<div class="tele-row"><span>SPEED</span><b id="speedValue">0.0 u/s</b></div>
<div class="tele-row"><span>PATH</span><b id="pathValue">0.0 u</b></div>
<div class="tele-row"><span>CONTACT</span><b id="contactValue">NONE</b></div>
<div class="tele-row"><span>LANDING</span><b id="validationValue">PENDING</b></div>
<div class="tele-row"><span>RUN TIME</span><b id="timeValue">00:00.0</b></div>
<div id="collisionMode">SWEPT SUBSTEP COLLISION · PROXIMITY NEVER SCORES</div>
</section>
<section id="controlPanel" class="hud panel">
<div class="control-help">
<strong><kbd>WASD</kbd> / arrows</strong> thrusters<br>
arm the next fixed vector
</div>
<div id="relayButtons">
<button class="relay-button" data-relay="1"><b>1</b>DOWN</button>
<button class="relay-button" data-relay="2"><b>2</b>RIGHT</button>
<button class="relay-button" data-relay="3"><b>3</b>UP</button>
<button class="relay-button" data-relay="4"><b>4</b>LEFT</button>
</div>
<button id="resetButton" class="small-button">RESTART RUN</button>
</section>
<div id="touchControls" aria-label="Touch thruster controls">
<button class="up" data-direction="up" aria-label="Thrust up">↑</button>
<button class="left" data-direction="left" aria-label="Thrust left">←</button>
<button class="down" data-direction="down" aria-label="Thrust down">↓</button>
<button class="right" data-direction="right" aria-label="Thrust right">→</button>
</div>
<div id="overlay" role="dialog" aria-modal="true"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Puzzle data. The gravity program is deliberately fixed and cannot be
// skipped or reordered. Each stage begins after the previous safe contact.
// -------------------------------------------------------------------------
const STAGES = [
{
key: 1,
direction: "DOWN",
name: "SEED",
gravity: new THREE.Vector2(0, -6),
launch: new THREE.Vector2(0, 12.4),
targetCenter: new THREE.Vector2(-6, 1.1),
targetSize: new THREE.Vector2(5, 1.4),
hazards: [
new THREE.Vector2(2.8, 6.2),
new THREE.Vector2(-1.8, 3.6)
],
guidance:
"Move left toward the top receiver. Tap UP against the fall to keep impact speed below 6.0 u/s."
},
{
key: 2,
direction: "RIGHT",
name: "CROSS",
gravity: new THREE.Vector2(6, 0),
launch: new THREE.Vector2(-8, 5.5),
targetCenter: new THREE.Vector2(8, 6),
targetSize: new THREE.Vector2(1.4, 5),
hazards: [
new THREE.Vector2(0, 3.3),
new THREE.Vector2(4, 8.1)
],
guidance:
"Gravity pulls RIGHT. Use UP/DOWN to line up with the left face, then thrust LEFT to brake."
},
{
key: 3,
direction: "UP",
name: "INVERT",
gravity: new THREE.Vector2(0, 6),
launch: new THREE.Vector2(7, 0.2),
targetCenter: new THREE.Vector2(-6, 14),
targetSize: new THREE.Vector2(5, 1.4),
hazards: [
new THREE.Vector2(2.5, 5.5),
new THREE.Vector2(-2.5, 10.5)
],
guidance:
"Inverted gravity pulls UP. Move LEFT toward the receiver and tap DOWN to soften contact."
},
{
key: 4,
direction: "LEFT",
name: "RETURN",
gravity: new THREE.Vector2(-6, 0),
launch: new THREE.Vector2(5, 13),
targetCenter: new THREE.Vector2(-9, 8),
targetSize: new THREE.Vector2(1.4, 5),
hazards: [
new THREE.Vector2(0, 10),
new THREE.Vector2(-3, 12)
],
guidance:
"Gravity pulls LEFT. Line up with the right face, then thrust RIGHT to reduce impact and sideways slip."
}
];
const FIXED_DT = 1 / 120;
const PLAYER_RADIUS = 0.42;
const THRUST_ACCELERATION = 14.5;
const MAX_SPEED = 17;
const MAX_NORMAL_IMPACT = 6.0;
const MAX_TANGENTIAL_SPEED = 7.5;
const WORLD = {
minX: -12.3,
maxX: 12.3,
minY: -1.4,
maxY: 17.4
};
const viewport = document.getElementById("viewport");
const overlay = document.getElementById("overlay");
const statusElement = document.getElementById("status");
const stageTitle = document.getElementById("stageTitle");
const sequenceElement = document.getElementById("sequence");
const gravityValue = document.getElementById("gravityValue");
const speedValue = document.getElementById("speedValue");
const pathValue = document.getElementById("pathValue");
const contactValue = document.getElementById("contactValue");
const validationValue = document.getElementById("validationValue");
const timeValue = document.getElementById("timeValue");
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
150
);
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
camera.aspect = aspect;
camera.updateProjectionMatrix();
// Fixed camera: no examples/addons or external camera controller.
const requiredDistance =
26 / (Math.tan(THREE.MathUtils.degToRad(camera.fov * 0.5)) * aspect);
camera.position.set(0, 8.3, Math.max(30, requiredDistance));
camera.lookAt(0, 8.3, 0);
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
}
window.addEventListener("resize", resize);
resize();
scene.add(new THREE.HemisphereLight(0xb7dcff, 0x142238, 1.8));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.1);
keyLight.position.set(-7, 13, 12);
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x3fbfff, 28, 30, 2);
rimLight.position.set(8, 5, 8);
scene.add(rimLight);
const worldRoot = new THREE.Group();
scene.add(worldRoot);
function createGrid() {
const positions = [];
const z = -1.25;
for (let x = -14; x <= 14; x += 2) {
positions.push(x, -2, z, x, 20, z);
}
for (let y = -2; y <= 20; y += 2) {
positions.push(-14, y, z, 14, y, z);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
const grid = new THREE.LineSegments(
geometry,
new THREE.LineBasicMaterial({
color: 0x5b82ad,
transparent: true,
opacity: 0.12,
depthWrite: false
})
);
worldRoot.add(grid);
const borderGeometry = new THREE.BufferGeometry();
borderGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute([
WORLD.minX, WORLD.minY, -0.9, WORLD.maxX, WORLD.minY, -0.9,
WORLD.maxX, WORLD.minY, -0.9, WORLD.maxX, WORLD.maxY, -0.9,
WORLD.maxX, WORLD.maxY, -0.9, WORLD.minX, WORLD.maxY, -0.9,
WORLD.minX, WORLD.maxY, -0.9, WORLD.minX, WORLD.minY, -0.9
], 3)
);
worldRoot.add(
new THREE.LineSegments(
borderGeometry,
new THREE.LineBasicMaterial({
color: 0x4c7197,
transparent: true,
opacity: 0.28
})
)
);
}
createGrid();
function createStars() {
const positions = [];
let seed = 7391;
const random = () => {
seed = (seed * 1664525 + 1013904223) >>> 0;
return seed / 4294967296;
};
for (let i = 0; i < 260; i++) {
positions.push(
(random() - 0.5) * 48,
(random() - 0.5) * 32,
-3 - random() * 14
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
const stars = new THREE.Points(
geometry,
new THREE.PointsMaterial({
color: 0x8bc9ee,
size: 0.065,
transparent: true,
opacity: 0.7,
sizeAttenuation: true,
depthWrite: false
})
);
worldRoot.add(stars);
}
createStars();
// Low-poly player probe.
const player = new THREE.Group();
const playerBody = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.43, 0),
new THREE.MeshStandardMaterial({
color: 0xe9f8ff,
flatShading: true,
roughness: 0.38,
metalness: 0.16,
emissive: 0x15384b,
emissiveIntensity: 0.45
})
);
player.add(playerBody);
const playerRing = new THREE.Mesh(
new THREE.TorusGeometry(0.55, 0.055, 4, 10),
new THREE.MeshStandardMaterial({
color: 0x58d8ff,
emissive: 0x1c91bd,
emissiveIntensity: 1.15,
flatShading: true,
roughness: 0.4
})
);
player.add(playerRing);
const playerNose = new THREE.Mesh(
new THREE.ConeGeometry(0.19, 0.52, 3),
new THREE.MeshStandardMaterial({
color: 0xffd479,
flatShading: true,
emissive: 0x6e4910,
emissiveIntensity: 0.3
})
);
playerNose.rotation.z = -Math.PI / 2;
playerNose.position.x = 0.49;
player.add(playerNose);
const playerLight = new THREE.PointLight(0x5fdcff, 4, 5, 2);
playerLight.position.z = 0.5;
player.add(playerLight);
player.position.z = 0.35;
worldRoot.add(player);
const gravityArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(),
2.1,
0xffd479,
0.5,
0.28
);
gravityArrow.visible = false;
worldRoot.add(gravityArrow);
const launchMarker = new THREE.Mesh(
new THREE.TorusGeometry(0.68, 0.055, 4, 12),
new THREE.MeshBasicMaterial({
color: 0x67d9ff,
transparent: true,
opacity: 0.7
})
);
launchMarker.position.z = 0.02;
worldRoot.add(launchMarker);
const guideLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: 0x4f8dc0,
transparent: true,
opacity: 0.32,
dashSize: 0.24,
gapSize: 0.17
})
);
worldRoot.add(guideLine);
const targetRoot = new THREE.Group();
worldRoot.add(targetRoot);
let targetMesh = null;
let targetLight = null;
const targetBox = {
minX: 0,
minY: 0,
maxX: 0,
maxY: 0
};
function clearTarget() {
while (targetRoot.children.length) {
const object = targetRoot.children.pop();
object.traverse(child => {
if (child.geometry) child.geometry.dispose();
if (child.material) {
const materials = Array.isArray(child.material)
? child.material
: [child.material];
for (const material of materials) {
if (material.map) material.map.dispose();
material.dispose();
}
}
});
}
}
function makeLabel(text) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(6, 18, 31, 0.92)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "rgba(120, 247, 176, 0.8)";
context.lineWidth = 5;
context.strokeRect(3, 3, canvas.width - 6, canvas.height - 6);
context.fillStyle = "#baffd7";
context.font = "800 42px ui-monospace, monospace";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2 + 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(3.25, 0.81, 1);
return sprite;
}
function buildTarget(stage) {
clearTarget();
targetBox.minX = stage.targetCenter.x - stage.targetSize.x / 2;
targetBox.maxX = stage.targetCenter.x + stage.targetSize.x / 2;
targetBox.minY = stage.targetCenter.y - stage.targetSize.y / 2;
targetBox.maxY = stage.targetCenter.y + stage.targetSize.y / 2;
const geometry = new THREE.BoxGeometry(
stage.targetSize.x,
stage.targetSize.y,
1.25
);
targetMesh = new THREE.Mesh(
geometry,
new THREE.MeshStandardMaterial({
color: 0x205f4a,
emissive: 0x167044,
emissiveIntensity: 0.8,
flatShading: true,
roughness: 0.48,
metalness: 0.18
})
);
targetMesh.position.set(
stage.targetCenter.x,
stage.targetCenter.y,
0
);
targetRoot.add(targetMesh);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: 0x91ffc7,
transparent: true,
opacity: 0.95
})
);
edges.position.copy(targetMesh.position);
targetRoot.add(edges);
const label = makeLabel(
`${stage.key} · ${stage.direction} / ${stage.name}`
);
label.position.set(
stage.targetCenter.x,
stage.targetCenter.y + stage.targetSize.y / 2 + 0.65,
1
);
targetRoot.add(label);
targetLight = new THREE.PointLight(0x5affa4, 5, 8, 2);
targetLight.position.set(
stage.targetCenter.x,
stage.targetCenter.y,
1.2
);
targetRoot.add(targetLight);
}
const hazardGroups = [];
for (let stageIndex = 0; stageIndex < STAGES.length; stageIndex++) {
const group = new THREE.Group();
for (let hazardIndex = 0; hazardIndex < STAGES[stageIndex].hazards.length; hazardIndex++) {
const position = STAGES[stageIndex].hazards[hazardIndex];
const hazard = new THREE.Mesh(
new THREE.ConeGeometry(0.6, 1.35, 4),
new THREE.MeshStandardMaterial({
color: 0xff6677,
emissive: 0x6d1022,
emissiveIntensity: 0.65,
flatShading: true,
roughness: 0.55
})
);
hazard.position.set(position.x, position.y, 0.12);
hazard.rotation.z = (hazardIndex % 2 ? 1 : -1) * 0.17;
group.add(hazard);
}
hazardGroups.push(group);
worldRoot.add(group);
}
// The path line contains only positions produced by the actual fixed-step
// physics integration. A landing is never awarded from marker proximity.
const MAX_TRAIL_POINTS = 1400;
const trailArray = new Float32Array(MAX_TRAIL_POINTS * 3);
const trailGeometry = new THREE.BufferGeometry();
trailGeometry.setAttribute(
"position",
new THREE.BufferAttribute(trailArray, 3)
);
trailGeometry.setDrawRange(0, 0);
const trail = new THREE.Line(
trailGeometry,
new THREE.LineBasicMaterial({
color: 0x67d9ff,
transparent: true,
opacity: 0.75
})
);
trail.frustumCulled = false;
worldRoot.add(trail);
let trailPointCount = 0;
function clearTrail() {
trailPointCount = 0;
trailGeometry.setDrawRange(0, 0);
trail.material.color.setHex(0x67d9ff);
}
function appendTrailPoint(position) {
if (trailPointCount >= MAX_TRAIL_POINTS) return;
const offset = trailPointCount * 3;
trailArray[offset] = position.x;
trailArray[offset + 1] = position.y;
trailArray[offset + 2] = -0.05;
trailPointCount++;
trailGeometry.setDrawRange(0, trailPointCount);
trailGeometry.attributes.position.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Game state
// -------------------------------------------------------------------------
let state = "intro";
let currentStage = 0;
let countdown = 0;
let successTimer = 0;
let totalTime = 0;
let pathLength = 0;
let lastImpact = null;
let contactType = "NONE";
let transientMessage = "";
let transientUntil = 0;
let audioContext = null;
const playerPosition = new THREE.Vector2();
const playerVelocity = new THREE.Vector2();
const currentGravity = new THREE.Vector2();
const completedStages = new Set();
const pressedKeys = new Set();
const touchDirections = new Set();
const directionCodes = {
left: ["ArrowLeft", "KeyA"],
right: ["ArrowRight", "KeyD"],
up: ["ArrowUp", "KeyW"],
down: ["ArrowDown", "KeyS"]
};
function formatTime(seconds) {
const minutes = Math.floor(seconds / 60);
const remaining = seconds - minutes * 60;
return `${String(minutes).padStart(2, "0")}:${remaining.toFixed(1).padStart(4, "0")}`;
}
function setNotice(text, duration = 2.2) {
transientMessage = text;
transientUntil = performance.now() + duration * 1000;
}
function updateSequenceUI() {
const chips = sequenceElement.querySelectorAll(".seq-chip");
chips.forEach((chip, index) => {
chip.classList.toggle("complete", completedStages.has(index));
chip.classList.toggle(
"active",
index === currentStage && state !== "success" && state !== "won"
);
});
const expectedKey = STAGES[currentStage]?.key;
document.querySelectorAll("[data-relay]").forEach(button => {
button.classList.toggle(
"expected",
Number(button.dataset.relay) === expectedKey && state === "armed"
);
});
}
sequenceElement.innerHTML = STAGES.map(stage => `
<div class="seq-chip">
<b>${stage.key}</b><span>${stage.direction}</span>
</div>
`).join("");
function prepareStage(index) {
currentStage = index;
const stage = STAGES[index];
playerPosition.copy(stage.launch);
playerVelocity.set(0, 0);
currentGravity.set(0, 0);
pathLength = 0;
lastImpact = null;
contactType = "NONE";
transientMessage = "";
transientUntil = 0;
state = "armed";
countdown = 0;
buildTarget(stage);
hazardGroups.forEach((group, groupIndex) => {
group.visible = groupIndex === index;
});
launchMarker.position.set(stage.launch.x, stage.launch.y, 0.02);
guideLine.geometry.dispose();
guideLine.geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(stage.launch.x, stage.launch.y, -0.05),
new THREE.Vector3(stage.targetCenter.x, stage.targetCenter.y, -0.05)
]);
guideLine.computeLineDistances();
clearTrail();
appendTrailPoint(playerPosition);
updateSequenceUI();
stageTitle.textContent =
`RELAY ${stage.key} / 4 · ${stage.name} · ${stage.direction}`;
}
function startRun() {
completedStages.clear();
totalTime = 0;
prepareStage(0);
overlay.classList.add("hidden");
ensureAudio();
setNotice(
`The order is locked. Press ${STAGES[0].key} to arm ${STAGES[0].direction} gravity.`,
3
);
}
function retryStage() {
prepareStage(currentStage);
overlay.classList.add("hidden");
setNotice(
`Press ${STAGES[currentStage].key} to re-arm ${STAGES[currentStage].direction} gravity.`,
3
);
}
function attemptArm(key) {
if (state !== "armed") return;
const expected = STAGES[currentStage].key;
if (key !== expected) {
setNotice(
`Relay order is fixed: ${expected} (${STAGES[currentStage].direction}) comes next.`
);
tone(130, 0.08, "square", 0.025);
return;
}
currentGravity.copy(STAGES[currentStage].gravity);
state = "countdown";
countdown = 1;
setNotice(
`${STAGES[currentStage].direction} vector armed. Fictional relay engaged.`,
2
);
tone(460 + key * 90, 0.12, "triangle", 0.045);
updateSequenceUI();
}
// -------------------------------------------------------------------------
// Actual collision tests
// -------------------------------------------------------------------------
function boxContact(point, radius) {
const closestX = THREE.MathUtils.clamp(
point.x,
targetBox.minX,
targetBox.maxX
);
const closestY = THREE.MathUtils.clamp(
point.y,
targetBox.minY,
targetBox.maxY
);
let dx = point.x - closestX;
let dy = point.y - closestY;
const distanceSquared = dx * dx + dy * dy;
if (distanceSquared > radius * radius) return null;
if (distanceSquared > 1e-10) {
const distance = Math.sqrt(distanceSquared);
return {
normal: new THREE.Vector2(dx / distance, dy / distance),
penetration: radius - distance
};
}
// Inside-the-box fallback, normally unreachable because collisions are
// resolved at first contact, but kept for numerical robustness.
const distances = [
point.x - targetBox.minX,
targetBox.maxX - point.x,
point.y - targetBox.minY,
targetBox.maxY - point.y
];
let nearest = 0;
for (let i = 1; i < distances.length; i++) {
if (distances[i] < distances[nearest]) nearest = i;
}
const normals = [
new THREE.Vector2(-1, 0),
new THREE.Vector2(1, 0),
new THREE.Vector2(0, -1),
new THREE.Vector2(0, 1)
];
return {
normal: normals[nearest].clone(),
penetration: radius
};
}
function sweepCircleBox(start, end, radius) {
// The fixed-step integration limits each substep to less than a fraction
// of the player radius, so no thin receiver can be tunneled through.
// Binary refinement locates the first actual intersecting point.
const samples = 4;
let previousT = 0;
for (let sample = 1; sample <= samples; sample++) {
const t = sample / samples;
const point = new THREE.Vector2().lerpVectors(start, end, t);
if (boxContact(point, radius)) {
let low = previousT;
let high = t;
for (let iteration = 0; iteration < 12; iteration++) {
const middle = (low + high) * 0.5;
const testPoint = new THREE.Vector2().lerpVectors(
start,
end,
middle
);
if (boxContact(testPoint, radius)) {
high = middle;
} else {
low = middle;
}
}
const hitPoint = new THREE.Vector2().lerpVectors(start, end, high);
const contact = boxContact(hitPoint, radius);
return contact ? { point: hitPoint, contact } : null;
}
previousT = t;
}
return null;
}
function sweepCircleCircle(start, end, center, radius) {
const direction = end.clone().sub(start);
const offset = start.clone().sub(center);
const a = direction.lengthSq();
const c = offset.lengthSq() - radius * radius;
if (c <= 0) {
return { t: 0, point: start.clone() };
}
if (a < 1e-12) return null;
const b = 2 * offset.dot(direction);
const discriminant = b * b - 4 * a * c;
if (discriminant < 0) return null;
const root = Math.sqrt(discriminant);
const t1 = (-b - root) / (2 * a);
const t2 = (-b + root) / (2 * a);
if (t1 >= 0 && t1 <= 1) {
return {
t: t1,
point: new THREE.Vector2().lerpVectors(start, end, t1)
};
}
if (t2 >= 0 && t2 <= 1) {
return {
t: t2,
point: new THREE.Vector2().lerpVectors(start, end, t2)
};
}
return null;
}
function failRun(reason, type) {
if (state === "failed" || state === "won") return;
state = "failed";
playerVelocity.set(0, 0);
contactType = type;
trail.material.color.setHex(0xff6b7d);
trailGeometry.attributes.position.needsUpdate = true;
if (targetMesh) {
targetMesh.material.color.setHex(0x71303d);
targetMesh.material.emissive.setHex(0x7d1528);
}
tone(105, 0.23, "sawtooth", 0.045);
if (navigator.vibrate) navigator.vibrate(80);
presentOverlay({
tag: "Run Interrupted",
title: type === "HAZARD" ? "Shard Contact" : "Unsafe Contact",
body: `
<p>${reason}</p>
<div class="truth-note">
<strong>Relay ${STAGES[currentStage].key} / 4 · ${STAGES[currentStage].direction}</strong><br>
A receiver only scores when the swept path physically touches the
gravity-facing surface at a safe speed.
</div>
`,
actions: [
{ label: "Retry Relay", primary: true, action: retryStage },
{ label: "Restart Run", primary: false, action: startRun }
]
});
}
function completeLanding(normalImpact, tangentialSpeed) {
if (state !== "playing") return;
state = "success";
successTimer = 0.9;
playerVelocity.set(0, 0);
lastImpact = normalImpact;
contactType = "RECEIVER";
completedStages.add(currentStage);
trail.material.color.setHex(0x78f7b0);
trailGeometry.attributes.position.needsUpdate = true;
if (targetMesh) {
targetMesh.material.color.setHex(0x4cff9a);
targetMesh.material.emissive.setHex(0x1dff83);
}
setNotice(
`Landing validated: ${normalImpact.toFixed(1)} u/s normal impact. ` +
(currentStage < 3
? `Next relay: ${STAGES[currentStage + 1].key} (${STAGES[currentStage + 1].direction}).`
: "All four gravity stages validated."),
3
);
tone(520, 0.09, "triangle", 0.05);
setTimeout(() => tone(690, 0.11, "triangle", 0.045), 85);
setTimeout(() => tone(860, 0.15, "triangle", 0.04), 170);
updateSequenceUI();
}
function resolveTargetCollision(hit) {
const normal = hit.contact.normal;
const expectedNormal = currentGravity.clone().normalize().multiplyScalar(-1);
const alignment = normal.dot(expectedNormal);
const normalImpact = Math.max(0, -playerVelocity.dot(normal));
const tangentSquared = Math.max(
0,
playerVelocity.lengthSq() - normalImpact * normalImpact
);
const tangentialSpeed = Math.sqrt(tangentSquared);
lastImpact = normalImpact;
contactType = "RECEIVER";
if (alignment < 0.72) {
failRun(
"The probe touched the receiver off its gravity-facing face. Approach the face toward which the current vector pulls.",
"RECEIVER"
);
return;
}
if (
normalImpact > MAX_NORMAL_IMPACT ||
tangentialSpeed > MAX_TANGENTIAL_SPEED
) {
failRun(
`Impact was unsafe: ${normalImpact.toFixed(1)} u/s normal and ` +
`${tangentialSpeed.toFixed(1)} u/s sideways slip. Limits are ` +
`${MAX_NORMAL_IMPACT.toFixed(1)} and ${MAX_TANGENTIAL_SPEED.toFixed(1)} u/s.`,
"RECEIVER"
);
return;
}
completeLanding(normalImpact, tangentialSpeed);
}
function integratePlayer(dt) {
const thrust = readThrust();
const acceleration = currentGravity.clone().addScaledVector(
thrust,
THRUST_ACCELERATION
);
playerVelocity.addScaledVector(acceleration, dt);
if (playerVelocity.length() > MAX_SPEED) {
playerVelocity.setLength(MAX_SPEED);
}
const travel = playerVelocity.length() * dt;
const substeps = Math.max(
1,
Math.ceil(travel / (PLAYER_RADIUS * 0.18))
);
const stepDt = dt / substeps;
for (let step = 0; step < substeps; step++) {
const start = playerPosition.clone();
const end = start.clone().addScaledVector(playerVelocity, stepDt);
for (const hazard of STAGES[currentStage].hazards) {
const hit = sweepCircleCircle(
start,
end,
hazard,
0.61
);
if (hit) {
playerPosition.copy(hit.point);
pathLength += start.distanceTo(hit.point);
appendTrailPoint(playerPosition);
failRun(
"A red shard intersected the probe's swept path. Use short corrective thrusts rather than crossing the shard field.",
"HAZARD"
);
return;
}
}
const targetHit = sweepCircleBox(
start,
end,
PLAYER_RADIUS
);
if (targetHit) {
playerPosition.copy(targetHit.point);
pathLength += start.distanceTo(targetHit.point);
appendTrailPoint(playerPosition);
resolveTargetCollision(targetHit);
return;
}
playerPosition.copy(end);
pathLength += start.distanceTo(end);
appendTrailPoint(playerPosition);
}
if (
playerPosition.x < WORLD.minX ||
playerPosition.x > WORLD.maxX ||
playerPosition.y < WORLD.minY ||
playerPosition.y > WORLD.maxY
) {
failRun(
"The probe crossed the simulation boundary. Its actual integrated path left the certified flight volume.",
"BOUNDARY"
);
}
}
function readThrust() {
let x = 0;
let y = 0;
const left =
touchDirections.has("left") ||
directionCodes.left.some(code => pressedKeys.has(code));
const right =
touchDirections.has("right") ||
directionCodes.right.some(code => pressedKeys.has(code));
const up =
touchDirections.has("up") ||
directionCodes.up.some(code => pressedKeys.has(code));
const down =
touchDirections.has("down") ||
directionCodes.down.some(code => pressedKeys.has(code));
if (left) x--;
if (right) x++;
if (up) y++;
if (down) y--;
const thrust = new THREE.Vector2(x, y);
if (thrust.lengthSq() > 1) thrust.normalize();
return thrust;
}
// -------------------------------------------------------------------------
// UI and input
// -------------------------------------------------------------------------
function presentOverlay({ tag, title, body, actions }) {
overlay.innerHTML = `
<section class="briefing">
<div class="eyebrow">${tag}</div>
<h2>${title}</h2>
${body}
<div class="overlay-actions"></div>
</section>
`;
const actionContainer = overlay.querySelector(".overlay-actions");
for (const action of actions) {
const button = document.createElement("button");
button.className = action.primary
? "primary-button"
: "secondary-button";
button.textContent = action.label;
button.addEventListener("click", action.action);
actionContainer.appendChild(button);
}
overlay.classList.remove("hidden");
}
function ensureAudio() {
if (!audioContext) {
const AudioContextClass =
window.AudioContext || window.webkitAudioContext;
if (AudioContextClass) audioContext = new AudioContextClass();
}
if (audioContext?.state === "suspended") audioContext.resume();
}
function tone(frequency, duration, type = "sine", volume = 0.04) {
if (!audioContext) return;
const oscillator = audioContext.createOscillator();
const gain = audioContext.createGain();
const now = audioContext.currentTime;
oscillator.type = type;
oscillator.frequency.setValueAtTime(frequency, now);
gain.gain.setValueAtTime(0.0001, now);
gain.gain.exponentialRampToValueAtTime(volume, now + 0.012);
gain.gain.exponentialRampToValueAtTime(0.0001, now + duration);
oscillator.connect(gain);
gain.connect(audioContext.destination);
oscillator.start(now);
oscillator.stop(now + duration + 0.02);
}
window.addEventListener("keydown", event => {
if (
event.code.startsWith("Arrow") ||
event.code === "Space" ||
event.code.startsWith("Key")
) {
event.preventDefault();
}
pressedKeys.add(event.code);
if (!event.repeat && /^[1-4]$/.test(event.key)) {
attemptArm(Number(event.key));
}
});
window.addEventListener("keyup", event => {
pressedKeys.delete(event.code);
});
window.addEventListener("blur", () => {
pressedKeys.clear();
touchDirections.clear();
});
document.querySelectorAll("[data-relay]").forEach(button => {
button.addEventListener("click", () => {
ensureAudio();
attemptArm(Number(button.dataset.relay));
});
});
document.querySelectorAll("[data-direction]").forEach(button => {
const direction = button.dataset.direction;
button.addEventListener("pointerdown", event => {
event.preventDefault();
button.setPointerCapture(event.pointerId);
touchDirections.add(direction);
});
const release = event => {
event.preventDefault();
touchDirections.delete(direction);
};
button.addEventListener("pointerup", release);
button.addEventListener("pointercancel", release);
button.addEventListener("lostpointercapture", release);
});
document.getElementById("resetButton").addEventListener("click", startRun);
function statusText() {
if (performance.now() < transientUntil) return transientMessage;
const stage = STAGES[currentStage];
switch (state) {
case "armed":
return `Press ${stage.key} to arm the scripted ${stage.direction} gravity vector. The relay order is locked.`;
case "countdown":
return `${stage.direction} vector armed. Brace for launch…`;
case "playing":
return stage.guidance;
case "success":
return "Safe landing validated. The relay is advancing the fixed sequence…";
case "failed":
return "The run was interrupted. Retry this relay or restart the full sequence.";
case "won":
return "All four certified landings completed.";
default:
return "Arm the scripted relay to begin.";
}
}
function updateHUD() {
const stage = STAGES[currentStage];
statusElement.textContent = statusText();
gravityValue.textContent = state === "armed"
? `PENDING ${stage.key}`
: stage.direction;
speedValue.textContent = `${playerVelocity.length().toFixed(1)} u/s`;
pathValue.textContent = `${pathLength.toFixed(1)} u`;
contactValue.textContent = contactType;
validationValue.textContent = lastImpact === null
? "PENDING"
: `${lastImpact.toFixed(1)} u/s`;
timeValue.textContent = formatTime(totalTime);
}
// -------------------------------------------------------------------------
// Intro and main loop
// -------------------------------------------------------------------------
prepareStage(0);
state = "intro";
updateSequenceUI();
presentOverlay({
tag: "Training Simulation / Fiction",
title: "Gravity Relay",
body: `
<p>
Complete four certified landings. After each contact, arm the next
gravity vector in this exact order:
<strong style="color:#78f7b0">1 DOWN → 2 RIGHT → 3 UP → 4 LEFT</strong>.
</p>
<div class="brief-grid">
<div class="brief-item">
<b>01 · THRUST</b>
<span>Hold WASD or the arrow keys. Opposite thrust can brake a fast approach.</span>
</div>
<div class="brief-item">
<b>02 · LAND</b>
<span>Touch the lit receiver's gravity-facing face. Keep normal impact at 6.0 u/s or less.</span>
</div>
<div class="brief-item">
<b>03 · SURVIVE</b>
<span>Red shards and the boundary fail the run. The actual swept path is what scores.</span>
</div>
</div>
<div class="truth-note">
<strong>Science boundary:</strong> selectable gravity is a fictional game
mechanic, not real antigravity technology. No verified portable device
can redirect gravity at the press of a button. The thrust controls
represent ordinary reaction-control propulsion.
</div>
`,
actions: [
{ label: "Begin Run", primary: true, action: startRun }
]
});
let previousTime = performance.now();
let accumulator = 0;
function frame(now) {
const frameDelta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (state === "countdown") {
countdown -= frameDelta;
if (countdown <= 0) {
state = "playing";
setNotice(STAGES[currentStage].guidance, 4);
updateSequenceUI();
}
} else if (state === "playing") {
accumulator += frameDelta;
while (accumulator >= FIXED_DT) {
totalTime += FIXED_DT;
integratePlayer(FIXED_DT);
accumulator -= FIXED_DT;
if (state !== "playing") {
accumulator = 0;
break;
}
}
} else {
accumulator = 0;
}
if (state === "success") {
successTimer -= frameDelta;
if (successTimer <= 0) {
if (currentStage === STAGES.length - 1) {
state = "won";
updateSequenceUI();
presentOverlay({
tag: "Sequence Complete",
title: "Four Landings Certified",
body: `
<p>
You completed the locked relay sequence and landed safely on
every gravity-facing receiver.
</p>
<div class="truth-note">
<strong>Run time: ${formatTime(totalTime)}</strong><br>
The result came from swept physical contacts and certified
impact speeds—not proximity markers or decorative animations.
</div>
`,
actions: [
{ label: "Run Again", primary: true, action: startRun }
]
});
} else {
prepareStage(currentStage + 1);
}
}
}
player.position.set(playerPosition.x, playerPosition.y, 0.35);
playerRing.rotation.z = now * 0.0011;
playerNose.rotation.y = Math.sin(now * 0.002) * 0.08;
if (currentGravity.lengthSq() > 0) {
gravityArrow.visible = true;
gravityArrow.position.set(playerPosition.x, playerPosition.y, 0.6);
gravityArrow.setDirection(
new THREE.Vector3(currentGravity.x, currentGravity.y, 0).normalize()
);
} else {
gravityArrow.visible = false;
}
if (targetMesh) {
const pulse = 1 + Math.sin(now * 0.004) * 0.014;
targetMesh.scale.set(pulse, pulse, 1);
targetMesh.material.emissiveIntensity =
0.75 + Math.sin(now * 0.004) * 0.22;
}
if (targetLight) {
targetLight.intensity = 4.5 + Math.sin(now * 0.005) * 1.2;
}
hazardGroups.forEach(group => {
group.children.forEach((hazard, index) => {
hazard.rotation.y = now * 0.0008 * (index % 2 ? -1 : 1);
});
});
launchMarker.rotation.z = now * 0.00035;
updateHUD();
renderer.render(scene, camera);
}
renderer.setAnimationLoop(frame);
</script>
</body>
</html>
```