Prompt specification
Build or customize the Three.js 3D scene "Gravity run with switching gate" 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: Gravity run with switching gate
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/gravity-run-with-switching-gate-x0354
Scene Description Prompt:
Release a marble down a fixed sloping channel and toggle the junction gate; the marble follows the selected branch without passing through the side walls. Build this with Three.js from cdnjs as a voxel scene in one HTML file.
Working Three.js Starter (gravity-run-with-switching-gate-x0354):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Junction</title>
<style>
:root {
color-scheme: dark;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #0a1020;
}
canvas {
position: fixed;
inset: 0;
z-index: 0;
display: block;
touch-action: none;
}
#hud {
position: fixed;
inset: 0;
z-index: 10;
display: flex;
align-items: flex-start;
justify-content: space-between;
padding: 20px;
pointer-events: none;
}
.panel {
width: min(340px, calc(100vw - 40px));
padding: 18px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 16px;
background: rgba(12, 18, 34, 0.82);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(14px);
pointer-events: auto;
}
h1 {
margin: 0 0 4px;
font-size: 22px;
letter-spacing: 0.04em;
}
.subtitle {
margin: 0 0 16px;
color: #9eabc2;
font-size: 13px;
line-height: 1.45;
}
.button-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
}
button {
min-height: 42px;
padding: 10px 12px;
border: 1px solid rgba(255, 255, 255, 0.14);
border-radius: 10px;
color: #f8fbff;
background: #26324a;
font: inherit;
font-size: 13px;
font-weight: 700;
cursor: pointer;
transition:
transform 120ms ease,
background 120ms ease,
border-color 120ms ease;
}
button:hover {
transform: translateY(-1px);
background: #33425f;
border-color: rgba(255, 255, 255, 0.25);
}
button:active {
transform: translateY(1px);
}
button.primary {
grid-column: 1 / -1;
color: #101828;
background: #ffbd59;
border-color: #ffd58e;
}
button.primary:hover {
background: #ffca76;
}
button.small {
min-height: 36px;
padding: 7px 12px;
}
.readouts {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 15px;
}
.readout {
padding: 10px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.055);
}
.label {
display: block;
margin-bottom: 4px;
color: #8290a8;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.value {
color: #f4f7fb;
font-size: 13px;
font-weight: 700;
}
.hint {
margin-top: 13px;
color: #8f9cb1;
font-size: 11px;
line-height: 1.55;
}
kbd {
padding: 2px 5px;
border: 1px solid rgba(255, 255, 255, 0.18);
border-bottom-width: 2px;
border-radius: 4px;
color: #dce4ef;
background: rgba(255, 255, 255, 0.07);
font: inherit;
font-size: 10px;
}
#help {
position: fixed;
right: 20px;
bottom: 18px;
z-index: 10;
padding: 8px 11px;
border-radius: 8px;
color: #a7b3c6;
background: rgba(9, 14, 27, 0.65);
font-size: 11px;
pointer-events: none;
}
@media (max-width: 700px) {
#hud {
padding: 12px;
}
.panel {
padding: 14px;
}
#help {
right: 12px;
bottom: 12px;
}
}
</style>
</head>
<body>
<div id="hud">
<section class="panel">
<h1>VOXEL JUNCTION</h1>
<p class="subtitle">
Release the marble, then switch the gate before it reaches the fork.
The open side determines the route.
</p>
<div class="button-grid">
<button id="release" class="primary">Release Marble</button>
<button id="gate">Gate: RIGHT Open</button>
<button id="reset">Reset</button>
<button id="nudgeLeft" class="small">← Nudge</button>
<button id="nudgeRight" class="small">Nudge →</button>
</div>
<div class="readouts">
<div class="readout">
<span class="label">Status</span>
<span id="status" class="value">Ready</span>
</div>
<div class="readout">
<span class="label">Route</span>
<span id="route" class="value">At junction</span>
</div>
<div class="readout">
<span class="label">Speed</span>
<span id="speed" class="value">0.0 m/s</span>
</div>
<div class="readout">
<span class="label">Gate</span>
<span id="gateState" class="value">Right open</span>
</div>
</div>
<div class="hint">
<kbd>Space</kbd> release ·
<kbd>←</kbd> <kbd>→</kbd> nudge ·
drag to orbit · wheel to zoom · right-drag to pan
</div>
</section>
</div>
<div id="help">Three.js core · fixed-step physics · wall-safe route</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a1020);
scene.fog = new THREE.Fog(0x0a1020, 22, 48);
const camera = new THREE.PerspectiveCamera(
48,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
document.body.appendChild(renderer.domElement);
const hemi = new THREE.HemisphereLight(0xb9d7ff, 0x182036, 2.15);
scene.add(hemi);
const sun = new THREE.DirectionalLight(0xfff1d2, 3.2);
sun.position.set(8, 18, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 16;
sun.shadow.camera.bottom = -13;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 48;
sun.shadow.bias = -0.0005;
const sunTarget = new THREE.Object3D();
sunTarget.position.set(0, 6, -1);
scene.add(sunTarget);
sun.target = sunTarget;
const rimLight = new THREE.DirectionalLight(0x5ea8ff, 1.25);
rimLight.position.set(-9, 7, -8);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Shared geometry and materials
// -------------------------------------------------------------------------
const cubeGeometry = new THREE.BoxGeometry(1, 1, 1);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x111a2b,
roughness: 0.96,
metalness: 0.02
});
const entryMaterial = new THREE.MeshStandardMaterial({
color: 0x496985,
roughness: 0.82,
metalness: 0.04,
emissive: 0x0a1825,
emissiveIntensity: 0.16
});
const leftMaterial = new THREE.MeshStandardMaterial({
color: 0x805339,
roughness: 0.82,
metalness: 0.04,
emissive: 0x000000,
emissiveIntensity: 0.05
});
const rightMaterial = new THREE.MeshStandardMaterial({
color: 0x397b72,
roughness: 0.82,
metalness: 0.04,
emissive: 0x000000,
emissiveIntensity: 0.05
});
const wallMaterial = new THREE.MeshStandardMaterial({
color: 0x28364d,
roughness: 0.74,
metalness: 0.12,
emissive: 0x18263b,
emissiveIntensity: 0.12
});
const supportMaterial = new THREE.MeshStandardMaterial({
color: 0x1b263a,
roughness: 0.94,
metalness: 0.03
});
const gateMaterial = new THREE.MeshStandardMaterial({
color: 0xffb13b,
roughness: 0.36,
metalness: 0.32,
emissive: 0x8a3b00,
emissiveIntensity: 0.48
});
// -------------------------------------------------------------------------
// Fixed channel centerlines
// -------------------------------------------------------------------------
const paths = {
entry: new THREE.CatmullRomCurve3(
[
new THREE.Vector3(-4.0, 12.0, -7.0),
new THREE.Vector3(-3.4, 10.8, -5.3),
new THREE.Vector3(-2.3, 9.4, -3.5),
new THREE.Vector3(-0.9, 8.1, -1.6),
new THREE.Vector3(0.0, 7.1, 0.0)
],
false,
"centripetal"
),
left: new THREE.CatmullRomCurve3(
[
new THREE.Vector3(0.0, 7.1, 0.0),
new THREE.Vector3(-1.6, 6.2, 1.3),
new THREE.Vector3(-3.8, 5.0, 3.0),
new THREE.Vector3(-6.6, 3.8, 5.3)
],
false,
"centripetal"
),
right: new THREE.CatmullRomCurve3(
[
new THREE.Vector3(0.0, 7.1, 0.0),
new THREE.Vector3(1.7, 6.2, 1.3),
new THREE.Vector3(4.0, 5.0, 3.0),
new THREE.Vector3(6.8, 3.8, 5.3)
],
false,
"centripetal"
)
};
for (const path of Object.values(paths)) {
path.length = path.getLength();
}
const CHANNEL_HALF_WIDTH = 1.1;
const MARBLE_RADIUS = 0.33;
const VOXEL_SIZE = 0.46;
// A frame at any point on a channel:
// p = floor surface point
// tangent = downhill direction
// side = horizontal direction across the channel
// up = floor normal
function frameAt(pathKey, distance) {
const path = paths[pathKey];
const u = THREE.MathUtils.clamp(distance / path.length, 0, 1);
const p = path.getPointAt(u);
const tangent = path.getTangentAt(u).normalize();
const side = new THREE.Vector3(
tangent.z,
0,
-tangent.x
);
if (side.lengthSq() < 0.000001) {
side.set(1, 0, 0);
}
side.normalize();
const up = new THREE.Vector3()
.crossVectors(tangent, side)
.normalize();
const basis = new THREE.Matrix4().makeBasis(side, up, tangent);
const quaternion = new THREE.Quaternion().setFromRotationMatrix(basis);
return { p, tangent, side, up, quaternion };
}
// -------------------------------------------------------------------------
// Voxel channel construction
// -------------------------------------------------------------------------
const floorTransforms = {
entry: [],
left: [],
right: []
};
const wallTransforms = [];
const supportTransforms = [];
function addBox(list, position, quaternion, scale) {
list.push({
position: position.clone(),
quaternion: quaternion.clone(),
scale: scale.clone()
});
}
for (const pathKey of Object.keys(paths)) {
const path = paths[pathKey];
// Floor blocks and two rows of side-wall blocks.
for (let s = 0; s <= path.length + 0.001; s += 0.42) {
const frame = frameAt(pathKey, s);
// Five floor voxels across the channel.
for (let column = -2; column <= 2; column++) {
const position = frame.p
.clone()
.addScaledVector(frame.side, column * VOXEL_SIZE)
.addScaledVector(frame.up, -VOXEL_SIZE * 0.5);
addBox(
floorTransforms[pathKey],
position,
frame.quaternion,
new THREE.Vector3(VOXEL_SIZE, VOXEL_SIZE, VOXEL_SIZE)
);
}
// Side walls. Their inner faces are exactly CHANNEL_HALF_WIDTH
// away from the centerline.
for (const sign of [-1, 1]) {
for (let row = 0; row < 2; row++) {
const position = frame.p
.clone()
.addScaledVector(
frame.side,
sign * (CHANNEL_HALF_WIDTH + VOXEL_SIZE * 0.5)
)
.addScaledVector(
frame.up,
VOXEL_SIZE * 0.5 + row * VOXEL_SIZE
);
addBox(
wallTransforms,
position,
frame.quaternion,
new THREE.Vector3(VOXEL_SIZE, VOXEL_SIZE, VOXEL_SIZE)
);
}
}
}
// Voxel support columns under the channel.
for (let s = 0.6; s < path.length; s += 1.15) {
const p = frameAt(pathKey, s).p;
for (let y = 0.24; y < p.y - 0.35; y += 0.48) {
addBox(
supportTransforms,
new THREE.Vector3(p.x, y, p.z),
new THREE.Quaternion(),
new THREE.Vector3(0.43, 0.43, 0.43)
);
}
}
}
function createInstancedBoxes(transforms, material) {
const mesh = new THREE.InstancedMesh(
cubeGeometry,
material,
transforms.length
);
const dummy = new THREE.Object3D();
transforms.forEach((transform, index) => {
dummy.position.copy(transform.position);
dummy.quaternion.copy(transform.quaternion);
dummy.scale.copy(transform.scale);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
});
mesh.instanceMatrix.needsUpdate = true;
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.computeBoundingSphere();
scene.add(mesh);
return mesh;
}
createInstancedBoxes(floorTransforms.entry, entryMaterial);
createInstancedBoxes(floorTransforms.left, leftMaterial);
createInstancedBoxes(floorTransforms.right, rightMaterial);
createInstancedBoxes(wallTransforms, wallMaterial);
createInstancedBoxes(supportTransforms, supportMaterial);
// Ground and grid.
const ground = new THREE.Mesh(
new THREE.BoxGeometry(19, 0.4, 16),
groundMaterial
);
ground.position.set(0, -0.23, -0.8);
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(18, 36, 0x304663, 0x1b2a42);
grid.position.set(0, -0.015, -0.8);
grid.material.transparent = true;
grid.material.opacity = 0.38;
scene.add(grid);
// -------------------------------------------------------------------------
// Labels
// -------------------------------------------------------------------------
function makeLabel(text, color) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(8, 14, 27, 0.82)";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = color;
context.lineWidth = 6;
context.strokeRect(4, 4, canvas.width - 8, canvas.height - 8);
context.fillStyle = color;
context.font = "bold 48px system-ui, sans-serif";
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
})
);
sprite.scale.set(2.8, 0.7, 1);
scene.add(sprite);
return sprite;
}
const entryStart = paths.entry.getPointAt(0);
const leftEnd = paths.left.getPointAt(1);
const rightEnd = paths.right.getPointAt(1);
makeLabel("RELEASE", "#a8c9f2").position.copy(entryStart).add(
new THREE.Vector3(0, 1.55, 0)
);
makeLabel("LEFT CHUTE", "#e8aa78").position.copy(leftEnd).add(
new THREE.Vector3(0, 1.2, 0)
);
makeLabel("RIGHT CHUTE", "#81ded1").position.copy(rightEnd).add(
new THREE.Vector3(0, 1.2, 0)
);
// -------------------------------------------------------------------------
// Junction gate
// -------------------------------------------------------------------------
const gateGroup = new THREE.Group();
for (let x = -1.05; x <= 1.051; x += 0.42) {
for (let row = 0; row < 2; row++) {
const block = new THREE.Mesh(cubeGeometry, gateMaterial);
block.scale.set(0.42, 0.42, 0.32);
block.position.set(x, 0.22 + row * 0.42, 0);
block.castShadow = true;
block.receiveShadow = true;
gateGroup.add(block);
}
}
scene.add(gateGroup);
// gateState names the side that is OPEN. The physical gate blocks the other.
let gateState = "right";
let gateSettled = true;
const gateTargetPosition = new THREE.Vector3();
const gateTargetQuaternion = new THREE.Quaternion();
function updateGateTarget() {
const blockedBranch = gateState === "right" ? "left" : "right";
const frame = frameAt(blockedBranch, 0.82);
gateTargetPosition.copy(frame.p);
gateTargetQuaternion.copy(frame.quaternion);
}
updateGateTarget();
gateGroup.position.copy(gateTargetPosition);
gateGroup.quaternion.copy(gateTargetQuaternion);
function updateGate(dt) {
const blend = 1 - Math.exp(-8 * dt);
gateGroup.position.lerp(gateTargetPosition, blend);
gateGroup.quaternion.slerp(gateTargetQuaternion, blend);
const positionSettled =
gateGroup.position.distanceToSquared(gateTargetPosition) < 0.0025;
const rotationSettled =
gateGroup.quaternion.angleTo(gateTargetQuaternion) < 0.035;
gateSettled = positionSettled && rotationSettled;
}
// -------------------------------------------------------------------------
// Marble texture, marble, trail, and impact particles
// -------------------------------------------------------------------------
function createMarbleTexture() {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
const context = canvas.getContext("2d");
context.fillStyle = "#eee9d7";
context.fillRect(0, 0, 256, 256);
context.lineCap = "round";
const orange = "#ef7c3c";
const blue = "#294d6b";
for (let offset = -220; offset < 460; offset += 66) {
context.beginPath();
context.strokeStyle = orange;
context.lineWidth = 17;
context.moveTo(offset, -30);
context.bezierCurveTo(
offset + 40,
55,
offset - 35,
145,
offset + 22,
285
);
context.stroke();
}
for (let offset = -160; offset < 420; offset += 91) {
context.beginPath();
context.strokeStyle = blue;
context.lineWidth = 7;
context.moveTo(offset, -25);
context.bezierCurveTo(
offset - 30,
85,
offset + 40,
165,
offset + 5,
285
);
context.stroke();
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const marbleMaterial = new THREE.MeshStandardMaterial({
map: createMarbleTexture(),
roughness: 0.2,
metalness: 0.08
});
const marble = new THREE.Mesh(
new THREE.SphereGeometry(MARBLE_RADIUS, 32, 24),
marbleMaterial
);
marble.castShadow = true;
marble.receiveShadow = true;
scene.add(marble);
const TRAIL_COUNT = 55;
const trailArray = new Float32Array(TRAIL_COUNT * 3);
const trailGeometry = new THREE.BufferGeometry();
trailGeometry.setAttribute(
"position",
new THREE.BufferAttribute(trailArray, 3)
);
trailGeometry.setDrawRange(0, 0);
const trail = new THREE.Points(
trailGeometry,
new THREE.PointsMaterial({
color: 0xffc46e,
size: 0.11,
transparent: true,
opacity: 0.72,
depthWrite: false
})
);
scene.add(trail);
const sparkGeometry = new THREE.BoxGeometry(0.11, 0.11, 0.11);
const sparkMaterial = new THREE.MeshBasicMaterial({
color: 0xffcf78
});
const sparks = [];
function spawnSparks(position) {
for (let i = 0; i < 7; i++) {
const spark = new THREE.Mesh(sparkGeometry, sparkMaterial);
spark.position.copy(position);
spark.rotation.set(
Math.random() * Math.PI,
Math.random() * Math.PI,
Math.random() * Math.PI
);
scene.add(spark);
sparks.push({
mesh: spark,
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 2.5,
0.7 + Math.random() * 1.8,
(Math.random() - 0.5) * 2.5
),
life: 0.42
});
}
}
let wallPulse = 0;
// -------------------------------------------------------------------------
// Simulation state
// -------------------------------------------------------------------------
const sim = {
mode: "ready", // ready, rolling, captured
path: "entry",
s: 0,
speed: 0,
lateral: 0,
lateralVelocity: 0,
selectedBranch: null,
waitingForGate: false,
time: 0
};
const FIXED_DT = 1 / 120;
const GRAVITY = 9.81;
const LATERAL_LIMIT =
CHANNEL_HALF_WIDTH - MARBLE_RADIUS - 0.035;
let trailCount = 0;
let trailTimer = 0;
function resetSimulation() {
sim.mode = "ready";
sim.path = "entry";
sim.s = 0;
sim.speed = 0;
sim.lateral = 0;
sim.lateralVelocity = 0;
sim.selectedBranch = null;
sim.waitingForGate = false;
trailCount = 0;
trailTimer = 0;
trailGeometry.setDrawRange(0, 0);
updateMarbleTransform();
}
function releaseMarble() {
if (sim.mode === "rolling") return;
resetSimulation();
sim.mode = "rolling";
sim.speed = 0.15;
}
function transitionAtJunction() {
sim.path = gateState;
sim.s = 0;
sim.selectedBranch = gateState;
sim.speed *= 0.86;
sim.lateral = 0;
sim.lateralVelocity = 0;
sim.waitingForGate = false;
}
function registerWallHit(sign) {
if (sim.hitCooldown > 0) return;
sim.hitCooldown = 0.13;
wallPulse = 1;
spawnSparks(marble.position);
}
sim.hitCooldown = 0;
function stepPhysics(dt) {
sim.time += dt;
sim.hitCooldown = Math.max(0, sim.hitCooldown - dt);
if (sim.mode !== "rolling") return;
const path = paths[sim.path];
const frame = frameAt(sim.path, sim.s);
// Gravity projected onto the channel tangent.
const downhillFactor = Math.max(0, -frame.tangent.y);
sim.speed += GRAVITY * downhillFactor * dt;
// Gentle rolling resistance.
sim.speed *= Math.exp(-0.16 * dt);
sim.speed = Math.min(sim.speed, 8);
let nextS = sim.s + sim.speed * dt;
if (sim.path === "entry" && nextS >= path.length) {
if (gateSettled) {
transitionAtJunction();
} else {
// Do not enter a moving gate. Wait at the junction until it settles.
sim.s = path.length;
sim.speed = 0;
sim.waitingForGate = true;
}
} else {
sim.s = Math.min(nextS, path.length);
}
// Lateral motion is damped and then swept against the inner wall plane.
// Clamping the final coordinate guarantees that the sphere never crosses
// a wall, even during a fast impact.
sim.lateralVelocity *= Math.exp(-2.2 * dt);
const previousLateral = sim.lateral;
const proposedLateral =
sim.lateral + sim.lateralVelocity * dt;
if (proposedLateral > LATERAL_LIMIT) {
sim.lateral = LATERAL_LIMIT;
if (previousLateral <= LATERAL_LIMIT && sim.lateralVelocity > 0) {
sim.lateralVelocity *= -0.42;
registerWallHit(1);
}
} else if (proposedLateral < -LATERAL_LIMIT) {
sim.lateral = -LATERAL_LIMIT;
if (previousLateral >= -LATERAL_LIMIT && sim.lateralVelocity < 0) {
sim.lateralVelocity *= -0.42;
registerWallHit(-1);
}
} else {
sim.lateral = proposedLateral;
}
if (
sim.path !== "entry" &&
sim.s >= paths[sim.path].length - 0.0001
) {
sim.mode = "captured";
sim.speed = 0;
}
}
function updateMarbleTransform() {
const frame = frameAt(sim.path, sim.s);
marble.position
.copy(frame.p)
.addScaledVector(frame.side, sim.lateral)
.addScaledVector(frame.up, MARBLE_RADIUS);
}
function pushTrail(position) {
trailArray.copyWithin(3, 0, (TRAIL_COUNT - 1) * 3);
trailArray[0] = position.x;
trailArray[1] = position.y;
trailArray[2] = position.z;
trailCount = Math.min(TRAIL_COUNT, trailCount + 1);
trailGeometry.attributes.position.needsUpdate = true;
trailGeometry.setDrawRange(0, trailCount);
}
function updateSparks(dt) {
wallPulse *= Math.exp(-8 * dt);
wallMaterial.emissiveIntensity = 0.12 + wallPulse * 0.55;
for (let i = sparks.length - 1; i >= 0; i--) {
const spark = sparks[i];
spark.life -= dt;
if (spark.life <= 0) {
scene.remove(spark.mesh);
sparks.splice(i, 1);
continue;
}
spark.velocity.y -= 8 * dt;
spark.mesh.position.addScaledVector(spark.velocity, dt);
spark.mesh.rotation.x += dt * 8;
spark.mesh.rotation.z += dt * 6;
spark.mesh.scale.setScalar(
Math.max(0.15, spark.life / 0.42)
);
}
}
// -------------------------------------------------------------------------
// Custom camera controls — no addons or legacy example scripts
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 7.0, -1.0);
let cameraYaw = 0.55;
let cameraPitch = 0.36;
let cameraDistance = 23.5;
let dragging = false;
let panning = false;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
panning = event.button === 2 || event.shiftKey;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (panning) {
const right = new THREE.Vector3(
Math.cos(cameraYaw),
0,
-Math.sin(cameraYaw)
);
cameraTarget.addScaledVector(
right,
-dx * cameraDistance * 0.0016
);
cameraTarget.y += dy * cameraDistance * 0.0016;
} else {
cameraYaw -= dx * 0.006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + dy * 0.0045,
0.1,
1.35
);
}
});
function endPointer(event) {
dragging = false;
panning = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraDistance = THREE.MathUtils.clamp(
cameraDistance * Math.exp(event.deltaY * 0.001),
11,
38
);
},
{ passive: false }
);
function updateCamera() {
const horizontalDistance =
Math.cos(cameraPitch) * cameraDistance;
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * horizontalDistance,
cameraTarget.y + Math.sin(cameraPitch) * cameraDistance,
cameraTarget.z + Math.cos(cameraYaw) * horizontalDistance
);
camera.lookAt(cameraTarget);
}
// -------------------------------------------------------------------------
// UI and input
// -------------------------------------------------------------------------
const releaseButton = document.getElementById("release");
const gateButton = document.getElementById("gate");
const resetButton = document.getElementById("reset");
const nudgeLeftButton = document.getElementById("nudgeLeft");
const nudgeRightButton = document.getElementById("nudgeRight");
const statusElement = document.getElementById("status");
const routeElement = document.getElementById("route");
const speedElement = document.getElementById("speed");
const gateStateElement = document.getElementById("gateState");
function refreshGateUI() {
gateButton.textContent = `Gate: ${gateState.toUpperCase()} Open`;
gateStateElement.textContent = `${gateState} open`;
leftMaterial.emissive.setHex(
gateState === "left" ? 0x1f6d50 : 0x000000
);
leftMaterial.emissiveIntensity =
gateState === "left" ? 0.42 : 0.05;
rightMaterial.emissive.setHex(
gateState === "right" ? 0x1f6d50 : 0x000000
);
rightMaterial.emissiveIntensity =
gateState === "right" ? 0.42 : 0.05;
}
function toggleGate() {
gateState = gateState === "right" ? "left" : "right";
gateSettled = false;
updateGateTarget();
refreshGateUI();
}
function nudge(direction) {
if (sim.mode !== "rolling") return;
sim.lateralVelocity = THREE.MathUtils.clamp(
sim.lateralVelocity + direction * 2.5,
-4.5,
4.5
);
}
releaseButton.addEventListener("click", releaseMarble);
gateButton.addEventListener("click", toggleGate);
resetButton.addEventListener("click", resetSimulation);
nudgeLeftButton.addEventListener("click", () => nudge(-1));
nudgeRightButton.addEventListener("click", () => nudge(1));
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
releaseMarble();
} else if (event.code === "ArrowLeft" || event.code === "KeyA") {
event.preventDefault();
nudge(-1);
} else if (event.code === "ArrowRight" || event.code === "KeyD") {
event.preventDefault();
nudge(1);
}
});
refreshGateUI();
resetSimulation();
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
let previousTime = performance.now();
let accumulator = 0;
function animate(now) {
const frameDt = Math.min(0.05, (now - previousTime) / 1000);
previousTime = now;
updateGate(frameDt);
accumulator += frameDt;
// Fixed-step integration prevents fast marbles from tunneling through
// the channel or skipping the gate transition.
while (accumulator >= FIXED_DT) {
stepPhysics(FIXED_DT);
accumulator -= FIXED_DT;
}
updateMarbleTransform();
updateSparks(frameDt);
updateCamera();
if (sim.mode === "rolling") {
marble.rotation.x += sim.speed * frameDt * 1.8;
marble.rotation.z += sim.speed * frameDt * 0.75;
trailTimer += frameDt;
if (trailTimer >= 0.028) {
trailTimer = 0;
pushTrail(marble.position);
}
}
let status = "Ready";
let route = "At junction";
if (sim.mode === "rolling") {
if (sim.waitingForGate) {
status = "Waiting at gate";
route = `${gateState.toUpperCase()} selected`;
} else if (sim.selectedBranch) {
status = "Rolling";
route = sim.selectedBranch.toUpperCase();
} else {
status = "Approaching fork";
route = "At junction";
}
} else if (sim.mode === "captured") {
status = "Captured";
route = sim.selectedBranch.toUpperCase();
}
statusElement.textContent = status;
routeElement.textContent = route;
speedElement.textContent = `${sim.speed.toFixed(1)} m/s`;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
</script>
</body>
</html>
```