Prompt specification
Build or customize the Three.js 3D scene "Shared turn-taking play mechanism" 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: Shared turn-taking play mechanism
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/shared-turn-taking-play-mechanism-x0442
Scene Description Prompt:
Two voxel visitors cooperate through opposite controls on one large rolling-ball panel, visibly changing the same ball's route. Three.js from cdnjs, one HTML file.
Working Three.js Starter (shared-turn-taking-play-mechanism-x0442):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Roll Together — Voxel Co-op</title>
<style>
:root {
--bg: #07111d;
--panel: rgba(12, 27, 43, 0.86);
--line: rgba(159, 205, 235, 0.18);
--text: #eaf7ff;
--muted: #90a9bb;
--amber: #ffb84d;
--cyan: #54d9ff;
--green: #78f2a9;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, sans-serif;
}
button { font: inherit; }
#app {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.hud {
position: fixed;
z-index: 10;
pointer-events: none;
}
#top-left {
top: 22px;
left: 24px;
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 0;
font-size: clamp(22px, 3vw, 39px);
line-height: 1;
letter-spacing: -0.045em;
text-shadow: 0 3px 20px rgba(0, 0, 0, 0.4);
}
h1 span { color: var(--amber); }
#route {
top: 25px;
left: 50%;
display: flex;
align-items: center;
gap: 8px;
transform: translateX(-50%);
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: var(--panel);
box-shadow: 0 12px 35px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(12px);
}
.step {
min-width: 58px;
padding: 7px 10px;
border: 1px solid rgba(255,255,255,0.08);
border-radius: 8px;
color: #688093;
background: rgba(255,255,255,0.025);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.11em;
text-align: center;
transition: 0.25s ease;
}
.step.active {
border-color: var(--cyan);
color: var(--cyan);
background: rgba(84, 217, 255, 0.1);
box-shadow: 0 0 18px rgba(84, 217, 255, 0.12);
}
.step.done {
border-color: rgba(120, 242, 169, 0.45);
color: var(--green);
background: rgba(120, 242, 169, 0.08);
}
.route-arrow {
color: #506779;
font-size: 12px;
}
#mission {
top: 27px;
right: 25px;
width: min(330px, 32vw);
padding: 12px 15px;
border: 1px solid var(--line);
border-radius: 12px;
background: var(--panel);
backdrop-filter: blur(12px);
}
#status {
color: var(--text);
font-size: 12px;
font-weight: 700;
line-height: 1.4;
}
#status::before {
content: "";
display: inline-block;
width: 7px;
height: 7px;
margin-right: 8px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 10px var(--cyan);
vertical-align: 1px;
}
.control-card {
bottom: 24px;
width: 235px;
padding: 15px;
border: 1px solid var(--line);
border-radius: 15px;
background: var(--panel);
box-shadow: 0 18px 45px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
pointer-events: auto;
}
#ember { left: 24px; }
#tide { right: 24px; }
.card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 10px;
}
.visitor-name {
font-size: 13px;
font-weight: 900;
letter-spacing: 0.08em;
}
.role {
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.amber .visitor-name { color: var(--amber); }
.cyan .visitor-name { color: var(--cyan); }
.keys {
display: flex;
gap: 7px;
margin-top: 11px;
}
.keys button {
flex: 1;
min-height: 42px;
border: 1px solid rgba(255,255,255,0.15);
border-bottom-width: 4px;
border-radius: 9px;
color: var(--text);
background: rgba(255,255,255,0.055);
cursor: pointer;
font-weight: 900;
transition: 0.08s ease;
user-select: none;
touch-action: none;
}
.keys button.pressed {
transform: translateY(2px);
border-bottom-width: 2px;
background: rgba(255,255,255,0.16);
}
.amber .keys button.pressed {
border-color: var(--amber);
color: var(--amber);
}
.cyan .keys button.pressed {
border-color: var(--cyan);
color: var(--cyan);
}
.meter {
position: relative;
height: 4px;
margin-top: 13px;
overflow: hidden;
border-radius: 10px;
background: rgba(255,255,255,0.08);
}
.meter i {
position: absolute;
top: 0;
bottom: 0;
left: 50%;
width: 3px;
border-radius: 5px;
background: var(--amber);
box-shadow: 0 0 8px var(--amber);
transform: translateX(-50%);
}
.cyan .meter i {
background: var(--cyan);
box-shadow: 0 0 8px var(--cyan);
}
#center-tip {
bottom: 27px;
left: 50%;
transform: translateX(-50%);
padding: 9px 13px;
border: 1px solid var(--line);
border-radius: 10px;
color: var(--muted);
background: rgba(7, 17, 29, 0.7);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.05em;
text-align: center;
backdrop-filter: blur(10px);
}
#center-tip b { color: var(--text); }
#utilities {
right: 24px;
top: 116px;
display: flex;
gap: 7px;
pointer-events: auto;
}
.utility {
padding: 8px 11px;
border: 1px solid var(--line);
border-radius: 8px;
color: var(--muted);
background: var(--panel);
cursor: pointer;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.07em;
}
.utility:hover { color: var(--text); }
#win {
position: fixed;
z-index: 30;
inset: 0;
display: grid;
place-items: center;
background: rgba(4, 10, 18, 0.56);
opacity: 0;
pointer-events: none;
transition: opacity 0.35s ease;
backdrop-filter: blur(5px);
}
#win.show {
opacity: 1;
pointer-events: auto;
}
.win-card {
width: min(390px, calc(100vw - 36px));
padding: 31px;
border: 1px solid rgba(120,242,169,0.4);
border-radius: 21px;
background: #0b1a2a;
box-shadow: 0 30px 100px rgba(0,0,0,0.5), 0 0 60px rgba(120,242,169,0.08);
text-align: center;
}
.win-icon {
display: grid;
width: 64px;
height: 64px;
margin: 0 auto 16px;
place-items: center;
border-radius: 18px;
color: #082017;
background: var(--green);
font-size: 32px;
font-weight: 900;
box-shadow: 0 0 35px rgba(120,242,169,0.25);
}
.win-card h2 {
margin: 7px 0 10px;
font-size: 29px;
letter-spacing: -0.035em;
}
.win-card p {
margin: 0 0 22px;
color: var(--muted);
font-size: 13px;
line-height: 1.6;
}
#play-again {
width: 100%;
padding: 13px;
border: 0;
border-radius: 10px;
color: #082017;
background: var(--green);
cursor: pointer;
font-weight: 900;
}
@media (max-width: 760px) {
#top-left { top: 16px; left: 16px; }
#route { top: 78px; }
#mission { display: none; }
.control-card {
bottom: 16px;
width: calc(50vw - 22px);
padding: 11px;
}
#ember { left: 12px; }
#tide { right: 12px; }
#center-tip { display: none; }
#utilities { top: 16px; right: 12px; }
.role { display: none; }
.keys button { min-height: 39px; }
}
</style>
</head>
<body>
<div id="app"></div>
<div id="top-left" class="hud">
<div class="eyebrow">Two visitors · one shared ball</div>
<h1>ROLL<span>//</span>TOGETHER</h1>
</div>
<div id="route" class="hud" aria-label="Route progress">
<div class="step active" id="step-0">START</div>
<div class="route-arrow">›</div>
<div class="step" id="step-1">LOW</div>
<div class="route-arrow">›</div>
<div class="step" id="step-2">HIGH</div>
<div class="route-arrow">›</div>
<div class="step" id="step-3">HOME</div>
</div>
<div id="mission" class="hud">
<div id="status" aria-live="polite">Guide the ball to the cyan LOW gate.</div>
</div>
<div id="utilities" class="hud">
<button class="utility" id="reset">RESET · R</button>
<button class="utility" id="camera-reset">VIEW</button>
</div>
<section id="ember" class="control-card amber hud">
<div class="card-head">
<div>
<div class="visitor-name">EMBER</div>
<div class="role">Left visitor · roll</div>
</div>
<div class="role">A / D</div>
</div>
<div class="keys">
<button data-key="KeyA" aria-label="Tilt left">A ◀</button>
<button data-key="KeyD" aria-label="Tilt right">▶ D</button>
</div>
<div class="meter"><i id="roll-needle"></i></div>
</section>
<section id="tide" class="control-card cyan hud">
<div class="card-head">
<div>
<div class="visitor-name">TIDE</div>
<div class="role">Right visitor · pitch</div>
</div>
<div class="role">↑ / ↓</div>
</div>
<div class="keys">
<button data-key="ArrowDown" aria-label="Tilt toward near edge">↓</button>
<button data-key="ArrowUp" aria-label="Tilt toward far edge">↑</button>
</div>
<div class="meter"><i id="pitch-needle"></i></div>
</section>
<div id="center-tip" class="hud">
<b>Hold</b> to tilt · release to level · <b>drag</b> to orbit · wheel to zoom
</div>
<div id="win">
<div class="win-card">
<div class="win-icon">✓</div>
<div class="eyebrow">Perfect cooperation</div>
<h2>Route complete!</h2>
<p>Both visitors aligned their controls and carried the same ball through every gate.</p>
<button id="play-again">PLAY AGAIN</button>
</div>
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Core scene
// -------------------------------------------------------------------------
const app = document.getElementById("app");
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111d);
scene.fog = new THREE.FogExp2(0x07111d, 0.021);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
180
);
const cameraTarget = new THREE.Vector3(0, 2.25, 0);
let cameraAzimuth = 0.56;
let cameraPolar = 0.77;
let cameraZoom = 1;
let baseCameraDistance = 30;
scene.add(new THREE.HemisphereLight(0xa7e7ff, 0x172131, 1.75));
const keyLight = new THREE.DirectionalLight(0xfff0d3, 2.65);
keyLight.position.set(-9, 18, 12);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -20;
keyLight.shadow.camera.right = 20;
keyLight.shadow.camera.top = 18;
keyLight.shadow.camera.bottom = -18;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 55;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4bcaff, 1.45);
rimLight.position.set(12, 8, -12);
scene.add(rimLight);
const standard = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.72,
metalness: 0.05,
...options
});
const mat = {
ground: standard(0x091522),
grid: new THREE.LineBasicMaterial({
color: 0x24465b,
transparent: true,
opacity: 0.35
}),
board: standard(0x143448, { roughness: 0.58, metalness: 0.16 }),
boardEdge: standard(0x244c62, { roughness: 0.45, metalness: 0.35 }),
dark: standard(0x07111a),
amber: standard(0xffad42, { roughness: 0.48 }),
cyan: standard(0x4ad5f6, { roughness: 0.45 }),
pink: standard(0xff6688, { roughness: 0.42 }),
green: standard(0x78f2a9, { roughness: 0.4 }),
white: standard(0xe9f6ff, { roughness: 0.58 }),
black: standard(0x04080c),
yellow: standard(0xffd45c, { roughness: 0.46 })
};
function addBox(parent, w, h, d, material, x = 0, y = 0, z = 0, shadow = true) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material);
mesh.position.set(x, y, z);
mesh.castShadow = shadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Ground and distant voxel scenery.
addBox(scene, 48, 0.45, 38, mat.ground, 0, -0.3, 0, false);
const grid = new THREE.GridHelper(80, 80, 0x31566b, 0x173246);
grid.position.y = -0.055;
grid.material.transparent = true;
grid.material.opacity = 0.35;
scene.add(grid);
const scenery = [
[-16, 1.4, -9, 2.1, 2.8, 2.1],
[-13, 0.8, -12, 1.4, 1.6, 1.4],
[15, 1.8, -10, 2.5, 3.6, 2.3],
[18, 1.0, -6, 1.7, 2.0, 1.7],
[-18, 0.7, 7, 1.2, 1.4, 1.2],
[17, 0.6, 8, 1.1, 1.2, 1.1]
];
for (const [x, y, z, w, h, d] of scenery) {
addBox(scene, w, h, d, standard(0x10283a), x, y, z);
addBox(scene, w * 0.72, 0.12, d * 0.72, standard(0x1b4054), x, y + h / 2 + 0.06, z);
}
// -------------------------------------------------------------------------
// Shared tilting panel
// -------------------------------------------------------------------------
const BOARD_W = 15;
const BOARD_D = 11;
const BALL_RADIUS = 0.42;
const MAX_ROLL = 0.285;
const MAX_PITCH = 0.265;
const board = new THREE.Group();
board.position.y = 3.2;
board.rotation.order = "ZXY";
scene.add(board);
addBox(board, BOARD_W, 0.7, BOARD_D, mat.board, 0, -0.35, 0);
addBox(board, BOARD_W + 0.2, 0.28, 0.22, mat.boardEdge, 0, 0.02, -BOARD_D / 2);
addBox(board, BOARD_W + 0.2, 0.28, 0.22, mat.boardEdge, 0, 0.02, BOARD_D / 2);
addBox(board, 0.22, 0.28, BOARD_D, mat.boardEdge, -BOARD_W / 2, 0.02, 0);
addBox(board, 0.22, 0.28, BOARD_D, mat.boardEdge, BOARD_W / 2, 0.02, 0);
const gridPositions = [];
for (let x = -BOARD_W / 2 + 1; x < BOARD_W / 2; x++) {
gridPositions.push(x, 0.012, -BOARD_D / 2, x, 0.012, BOARD_D / 2);
}
for (let z = -BOARD_D / 2 + 1; z < BOARD_D / 2; z++) {
gridPositions.push(-BOARD_W / 2, 0.012, z, BOARD_W / 2, 0.012, z);
}
const boardGridGeometry = new THREE.BufferGeometry();
boardGridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridPositions, 3)
);
board.add(new THREE.LineSegments(boardGridGeometry, mat.grid));
// Static center pedestal.
const pedestal = new THREE.Mesh(
new THREE.CylinderGeometry(1.2, 2.25, 1.65, 16),
standard(0x172f42, { metalness: 0.35 })
);
pedestal.position.y = 0.82;
pedestal.castShadow = true;
pedestal.receiveShadow = true;
scene.add(pedestal);
const pivot = new THREE.Mesh(
new THREE.CylinderGeometry(1.35, 1.35, 0.5, 20),
mat.cyan
);
pivot.position.y = 2.87;
pivot.castShadow = true;
scene.add(pivot);
// -------------------------------------------------------------------------
// Obstacles and route gates
// -------------------------------------------------------------------------
const obstacleData = [
{ x: -3.8, z: 0.45, w: 0.72, d: 4.1 },
{ x: 0.2, z: 0.0, w: 4.3, d: 0.62 },
{ x: 4.35, z: 0.65, w: 0.72, d: 4.3 }
];
for (const ob of obstacleData) {
addBox(board, ob.w, 0.88, ob.d, mat.dark, ob.x, 0.44, ob.z);
addBox(
board,
ob.w + 0.06,
0.13,
ob.d + 0.06,
mat.yellow,
ob.x,
0.92,
ob.z
);
// Small voxel warning lights.
const lightCount = Math.max(2, Math.floor(ob.d / 1.3));
for (let i = 0; i < lightCount; i++) {
const z = ob.z - ob.d / 2 + (i + 0.5) * (ob.d / lightCount);
addBox(
board,
ob.w * 0.72,
0.08,
0.18,
mat.amber,
ob.x,
1.02,
z,
false
);
}
}
const checkpointData = [
{ x: -2.7, z: -3.4, color: 0x54d9ff, name: "LOW" },
{ x: 2.7, z: 3.4, color: 0xffd166, name: "HIGH" },
{ x: 6.0, z: -3.5, color: 0xff6688, name: "HOME" }
];
function makeLabel(text, color = "#dff7ff") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 160;
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgba(7,17,29,0.9)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = color;
ctx.lineWidth = 7;
ctx.strokeRect(4, 4, canvas.width - 8, canvas.height - 8);
ctx.fillStyle = color;
ctx.font = "900 58px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.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,
depthWrite: false
})
);
sprite.scale.set(3.05, 0.95, 1);
return sprite;
}
const checkpoints = checkpointData.map((cp, index) => {
const group = new THREE.Group();
group.position.set(cp.x, 0, cp.z);
board.add(group);
const color = new THREE.Color(cp.color);
const ringMaterial = standard(cp.color, {
emissive: cp.color,
emissiveIntensity: index === 0 ? 2.1 : 0.3,
roughness: 0.3,
metalness: 0.2
});
const upright = new THREE.Mesh(
new THREE.TorusGeometry(1.02, 0.115, 8, 32),
ringMaterial
);
upright.position.y = 1.02;
upright.castShadow = true;
group.add(upright);
const base = new THREE.Mesh(
new THREE.TorusGeometry(1.02, 0.055, 6, 32),
ringMaterial
);
base.rotation.x = Math.PI / 2;
base.position.y = 0.06;
group.add(base);
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.23),
ringMaterial
);
marker.position.y = 2.35;
group.add(marker);
const light = new THREE.PointLight(cp.color, index === 0 ? 4.5 : 1.3, 5, 2);
light.position.y = 1.4;
group.add(light);
const label = makeLabel(`${index + 1} ${cp.name}`, `#${color.getHexString()}`);
label.position.set(0, 2.95, 0);
label.scale.set(2.35, 0.73, 1);
group.add(label);
if (index === checkpointData.length - 1) {
const receiver = new THREE.Mesh(
new THREE.CylinderGeometry(0.82, 0.92, 0.28, 24),
mat.dark
);
receiver.position.y = 0.14;
receiver.castShadow = true;
group.add(receiver);
const receiverLip = new THREE.Mesh(
new THREE.TorusGeometry(0.8, 0.085, 8, 32),
ringMaterial
);
receiverLip.rotation.x = Math.PI / 2;
receiverLip.position.y = 0.3;
group.add(receiverLip);
}
return {
...cp,
group,
ring: upright,
marker,
material: ringMaterial,
light,
flash: 0
};
});
// Start pad.
const startPad = new THREE.Mesh(
new THREE.TorusGeometry(0.68, 0.075, 6, 24),
standard(0x8ba8bb, { emissive: 0x8ba8bb, emissiveIntensity: 0.35 })
);
startPad.rotation.x = Math.PI / 2;
startPad.position.set(-6.05, 0.045, 4.0);
board.add(startPad);
// -------------------------------------------------------------------------
// Shared ball and trail
// -------------------------------------------------------------------------
const ballGroup = new THREE.Group();
const ball = new THREE.Mesh(
new THREE.SphereGeometry(BALL_RADIUS, 24, 16),
standard(0xff9e3d, {
roughness: 0.22,
metalness: 0.32,
emissive: 0x7a2700,
emissiveIntensity: 0.13
})
);
ball.castShadow = true;
ball.receiveShadow = true;
ballGroup.add(ball);
const ballBand = new THREE.Mesh(
new THREE.TorusGeometry(BALL_RADIUS * 1.01, 0.035, 6, 28),
standard(0xffe6aa, { roughness: 0.3, metalness: 0.5 })
);
ballBand.rotation.x = Math.PI / 2;
ballGroup.add(ballBand);
board.add(ballGroup);
const MAX_TRAIL = 150;
const trailArray = new Float32Array(MAX_TRAIL * 3);
const trailGeometry = new THREE.BufferGeometry();
trailGeometry.setAttribute(
"position",
new THREE.BufferAttribute(trailArray, 3).setUsage(THREE.DynamicDrawUsage)
);
trailGeometry.setDrawRange(0, 0);
const trail = new THREE.Line(
trailGeometry,
new THREE.LineBasicMaterial({
color: 0xffb84d,
transparent: true,
opacity: 0.72
})
);
trail.position.y = 0.045;
board.add(trail);
let trailCount = 0;
let trailTimer = 0;
// -------------------------------------------------------------------------
// Voxel visitors and their physical control levers
// -------------------------------------------------------------------------
function createVisitor(x, bodyMaterial, accentMaterial, labelText, labelColor) {
const root = new THREE.Group();
root.position.set(x, 0.28, 1.45);
scene.add(root);
addBox(scene, 2.35, 0.3, 2.2, mat.boardEdge, x, 0.15, 1.45);
addBox(scene, 1.95, 0.08, 1.8, mat.dark, x, 0.33, 1.45);
addBox(root, 0.34, 0.65, 0.39, mat.dark, -0.25, 0.34, 0);
addBox(root, 0.34, 0.65, 0.39, mat.dark, 0.25, 0.34, 0);
addBox(root, 0.39, 0.2, 0.58, mat.white, -0.25, 0.08, 0.1);
addBox(root, 0.39, 0.2, 0.58, mat.white, 0.25, 0.08, 0.1);
addBox(root, 0.95, 0.95, 0.67, bodyMaterial, 0, 1.11, 0);
addBox(root, 0.4, 0.44, 0.08, accentMaterial, 0, 1.15, 0.38);
addBox(root, 0.85, 0.82, 0.75, bodyMaterial, 0, 2.02, 0);
addBox(root, 0.12, 0.14, 0.05, mat.black, -0.19, 2.07, 0.4);
addBox(root, 0.12, 0.14, 0.05, mat.black, 0.19, 2.07, 0.4);
addBox(root, 0.22, 0.06, 0.05, mat.white, 0, 1.87, 0.405);
addBox(root, 1.02, 0.2, 0.82, accentMaterial, 0, 2.48, 0);
addBox(root, 0.62, 0.18, 0.48, accentMaterial, 0, 2.64, 0);
const leftArm = new THREE.Group();
leftArm.position.set(-0.64, 1.51, 0);
root.add(leftArm);
addBox(leftArm, 0.28, 0.7, 0.32, bodyMaterial, 0, -0.3, 0);
addBox(leftArm, 0.3, 0.25, 0.34, mat.white, 0, -0.7, 0);
const rightArm = new THREE.Group();
rightArm.position.set(0.64, 1.51, 0);
root.add(rightArm);
addBox(rightArm, 0.28, 0.7, 0.32, bodyMaterial, 0, -0.3, 0);
addBox(rightArm, 0.3, 0.25, 0.34, mat.white, 0, -0.7, 0);
const label = makeLabel(labelText, labelColor);
label.position.set(0, 3.55, 0);
label.scale.set(2.5, 0.78, 1);
root.add(label);
return { root, leftArm, rightArm };
}
const ember = createVisitor(
-9.35,
mat.amber,
standard(0x6b3518),
"EMBER · A / D",
"#ffbf5b"
);
const tide = createVisitor(
9.35,
mat.cyan,
standard(0x164b62),
"TIDE · ↑ / ↓",
"#65ddff"
);
function createLever(x, color) {
const root = new THREE.Group();
root.position.set(x, 0.35, 1.45);
scene.add(root);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.46, 0.58, 0.26, 12),
mat.boardEdge
);
base.position.y = 0.13;
base.castShadow = true;
root.add(base);
const pivotGroup = new THREE.Group();
pivotGroup.position.y = 0.28;
root.add(pivotGroup);
addBox(pivotGroup, 0.17, 1.3, 0.17, mat.dark, 0, 0.62, 0);
addBox(pivotGroup, 0.7, 0.19, 0.25, color, 0, 1.25, 0);
return pivotGroup;
}
const emberLever = createLever(-8.03, mat.amber);
const tideLever = createLever(8.03, mat.cyan);
// -------------------------------------------------------------------------
// Input
// -------------------------------------------------------------------------
const keys = new Set();
window.addEventListener("keydown", (event) => {
if (
event.code.startsWith("Arrow") ||
event.code === "Space" ||
event.code === "KeyR"
) {
event.preventDefault();
}
keys.add(event.code);
if (event.code === "KeyR") resetGame();
});
window.addEventListener("keyup", (event) => {
keys.delete(event.code);
});
window.addEventListener("blur", () => keys.clear());
document.querySelectorAll("[data-key]").forEach((button) => {
const code = button.dataset.key;
button.addEventListener("pointerdown", (event) => {
event.preventDefault();
keys.add(code);
button.classList.add("pressed");
button.setPointerCapture?.(event.pointerId);
});
const release = () => {
keys.delete(code);
button.classList.remove("pressed");
};
button.addEventListener("pointerup", release);
button.addEventListener("pointercancel", release);
button.addEventListener("lostpointercapture", release);
});
// -------------------------------------------------------------------------
// Direct camera controls, implemented without addons
// -------------------------------------------------------------------------
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
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;
cameraAzimuth -= dx * 0.006;
cameraPolar = THREE.MathUtils.clamp(
cameraPolar + dy * 0.005,
0.43,
1.12
);
});
const endDrag = () => { dragging = false; };
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraZoom = THREE.MathUtils.clamp(
cameraZoom + event.deltaY * 0.00075,
0.68,
1.55
);
},
{ passive: false }
);
function resetCamera() {
cameraAzimuth = 0.56;
cameraPolar = 0.77;
cameraZoom = 1;
}
document.getElementById("camera-reset").addEventListener("click", resetCamera);
// -------------------------------------------------------------------------
// Game state and UI
// -------------------------------------------------------------------------
const statusElement = document.getElementById("status");
const winElement = document.getElementById("win");
const rollNeedle = document.getElementById("roll-needle");
const pitchNeedle = document.getElementById("pitch-needle");
const stepElements = [...document.querySelectorAll(".step")];
const statusMessages = [
"Guide the ball to the cyan LOW gate.",
"LOW cleared. Now carry the ball to the HIGH gate.",
"HIGH cleared. Guide the ball into the HOME receiver.",
"Every gate cleared — perfect teamwork!"
];
let progressIndex = 0;
let won = false;
let ballVX = 0;
let ballVZ = 0;
let roll = 0;
let pitch = 0;
let rollTarget = 0;
let pitchTarget = 0;
let elapsed = 0;
function updateHUD() {
statusElement.textContent = statusMessages[progressIndex];
stepElements.forEach((step, index) => {
step.classList.toggle("done", index < progressIndex);
step.classList.toggle("active", index === progressIndex && !won);
});
}
function resetGame() {
progressIndex = 0;
won = false;
ballVX = 0;
ballVZ = 0;
roll = 0;
pitch = 0;
rollTarget = 0;
pitchTarget = 0;
ballGroup.position.set(-6.05, BALL_RADIUS, 4.0);
ballGroup.rotation.set(0, 0, 0);
board.rotation.set(0, 0, 0, "ZXY");
trailCount = 0;
trailGeometry.setDrawRange(0, 0);
checkpoints.forEach((checkpoint) => {
checkpoint.flash = 0;
});
winElement.classList.remove("show");
updateHUD();
}
document.getElementById("reset").addEventListener("click", resetGame);
document.getElementById("play-again").addEventListener("click", resetGame);
// -------------------------------------------------------------------------
// Celebration particles
// -------------------------------------------------------------------------
const confettiGeometry = new THREE.BoxGeometry(0.13, 0.13, 0.13);
const confettiMaterials = [
standard(0x54d9ff, { emissive: 0x113b46, emissiveIntensity: 0.4 }),
standard(0xffb84d, { emissive: 0x4b2600, emissiveIntensity: 0.4 }),
standard(0xff6688),
standard(0x78f2a9)
];
const particles = [];
function burst(position, amount = 36) {
for (let i = 0; i < amount; i++) {
const mesh = new THREE.Mesh(
confettiGeometry,
confettiMaterials[i % confettiMaterials.length]
);
mesh.position.copy(position);
mesh.rotation.set(
Math.random() * Math.PI,
Math.random() * Math.PI,
Math.random() * Math.PI
);
const velocity = new THREE.Vector3(
(Math.random() - 0.5) * 6,
2.5 + Math.random() * 5,
(Math.random() - 0.5) * 6
);
scene.add(mesh);
particles.push({ mesh, velocity, life: 2.8 });
}
}
function updateParticles(dt) {
for (let i = particles.length - 1; i >= 0; i--) {
const particle = particles[i];
particle.life -= dt;
particle.velocity.y -= 8.5 * dt;
particle.mesh.position.addScaledVector(particle.velocity, dt);
particle.mesh.rotation.x += dt * 5;
particle.mesh.rotation.z += dt * 4;
if (particle.life <= 0) {
scene.remove(particle.mesh);
particles.splice(i, 1);
}
}
}
// -------------------------------------------------------------------------
// Physics helpers
// -------------------------------------------------------------------------
function damp(current, target, speed, dt) {
return THREE.MathUtils.lerp(
current,
target,
1 - Math.exp(-speed * dt)
);
}
function resolveCircleBox(obstacle) {
const minX = obstacle.x - obstacle.w / 2;
const maxX = obstacle.x + obstacle.w / 2;
const minZ = obstacle.z - obstacle.d / 2;
const maxZ = obstacle.z + obstacle.d / 2;
const closestX = THREE.MathUtils.clamp(ballGroup.position.x, minX, maxX);
const closestZ = THREE.MathUtils.clamp(ballGroup.position.z, minZ, maxZ);
let dx = ballGroup.position.x - closestX;
let dz = ballGroup.position.z - closestZ;
const distanceSquared = dx * dx + dz * dz;
if (distanceSquared >= BALL_RADIUS * BALL_RADIUS) return;
let normalX = 0;
let normalZ = 0;
let penetration = 0;
if (distanceSquared > 0.000001) {
const distance = Math.sqrt(distanceSquared);
normalX = dx / distance;
normalZ = dz / distance;
penetration = BALL_RADIUS - distance;
} else {
const toLeft = ballGroup.position.x - minX;
const toRight = maxX - ballGroup.position.x;
const toBottom = ballGroup.position.z - minZ;
const toTop = maxZ - ballGroup.position.z;
const minimum = Math.min(toLeft, toRight, toBottom, toTop);
if (minimum === toLeft) {
normalX = -1;
penetration = BALL_RADIUS + toLeft;
} else if (minimum === toRight) {
normalX = 1;
penetration = BALL_RADIUS + toRight;
} else if (minimum === toBottom) {
normalZ = -1;
penetration = BALL_RADIUS + toBottom;
} else {
normalZ = 1;
penetration = BALL_RADIUS + toTop;
}
}
ballGroup.position.x += normalX * penetration;
ballGroup.position.z += normalZ * penetration;
const normalVelocity = ballVX * normalX + ballVZ * normalZ;
if (normalVelocity < 0) {
ballVX -= 1.35 * normalVelocity * normalX;
ballVZ -= 1.35 * normalVelocity * normalZ;
}
}
function constrainToBoard() {
const limitX = BOARD_W / 2 - BALL_RADIUS;
const limitZ = BOARD_D / 2 - BALL_RADIUS;
if (ballGroup.position.x < -limitX) {
ballGroup.position.x = -limitX;
ballVX = Math.abs(ballVX) * 0.42;
} else if (ballGroup.position.x > limitX) {
ballGroup.position.x = limitX;
ballVX = -Math.abs(ballVX) * 0.42;
}
if (ballGroup.position.z < -limitZ) {
ballGroup.position.z = -limitZ;
ballVZ = Math.abs(ballVZ) * 0.42;
} else if (ballGroup.position.z > limitZ) {
ballGroup.position.z = limitZ;
ballVZ = -Math.abs(ballVZ) * 0.42;
}
}
function activateCheckpoint(index) {
if (index !== progressIndex) return;
progressIndex++;
checkpoints[index].flash = 1;
board.updateMatrixWorld(true);
const burstPosition = new THREE.Vector3();
checkpoints[index].group.getWorldPosition(burstPosition);
burstPosition.y += 1;
burst(burstPosition, 28);
if (progressIndex === checkpoints.length) {
won = true;
ballVX = 0;
ballVZ = 0;
winElement.classList.add("show");
}
updateHUD();
}
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.033);
elapsed += dt;
const rollInput =
Number(keys.has("KeyA") || keys.has("ArrowLeft")) -
Number(keys.has("KeyD") || keys.has("ArrowRight"));
const pitchInput =
Number(keys.has("ArrowUp") || keys.has("KeyW")) -
Number(keys.has("ArrowDown") || keys.has("KeyS"));
rollTarget = damp(rollTarget, rollInput * MAX_ROLL, 6.2, dt);
pitchTarget = damp(pitchTarget, pitchInput * MAX_PITCH, 6.2, dt);
roll = damp(roll, rollTarget, 8.2, dt);
pitch = damp(pitch, pitchTarget, 8.2, dt);
board.rotation.set(pitch, 0, roll, "ZXY");
const rollNormalized = roll / MAX_ROLL;
const pitchNormalized = pitch / MAX_PITCH;
// Visitor and lever animations make each control visibly active.
ember.root.rotation.z = -rollNormalized * 0.065;
ember.rightArm.rotation.z = 1.02 + rollNormalized * 0.22;
ember.leftArm.rotation.z = -0.18 - Math.abs(rollNormalized) * 0.08;
emberLever.rotation.z = -rollNormalized * 0.55;
tide.root.rotation.x = pitchNormalized * 0.055;
tide.leftArm.rotation.z = -1.02 + pitchNormalized * 0.2;
tide.rightArm.rotation.z = 0.18 + Math.abs(pitchNormalized) * 0.08;
tideLever.rotation.x = pitchNormalized * 0.55;
const idle = Math.sin(elapsed * 2.2) * 0.012;
ember.root.position.y = 0.28 + idle;
tide.root.position.y = 0.28 - idle;
rollNeedle.style.left = `${50 + rollNormalized * 46}%`;
pitchNeedle.style.left = `${50 + pitchNormalized * 46}%`;
if (!won) {
// Tangential gravity in the board's local coordinates.
const accelerationX = -7.8 * Math.sin(roll) * 0.73;
const accelerationZ = -7.8 * Math.sin(pitch) * 0.73;
ballVX += accelerationX * dt;
ballVZ += accelerationZ * dt;
const rollingResistance = Math.exp(-0.24 * dt);
ballVX *= rollingResistance;
ballVZ *= rollingResistance;
const speed = Math.hypot(ballVX, ballVZ);
if (speed > 7.5) {
ballVX = (ballVX / speed) * 7.5;
ballVZ = (ballVZ / speed) * 7.5;
}
ballGroup.position.x += ballVX * dt;
ballGroup.position.z += ballVZ * dt;
obstacleData.forEach(resolveCircleBox);
constrainToBoard();
const nextCheckpoint = checkpoints[progressIndex];
if (nextCheckpoint) {
const dx = ballGroup.position.x - nextCheckpoint.x;
const dz = ballGroup.position.z - nextCheckpoint.z;
if (dx * dx + dz * dz < 0.98 * 0.98) {
activateCheckpoint(progressIndex);
}
}
}
// Visible rolling of the shared ball.
ballGroup.rotation.z -= (ballVX / BALL_RADIUS) * dt;
ballGroup.rotation.x += (ballVZ / BALL_RADIUS) * dt;
// Route trail.
trailTimer += dt;
if (trailTimer > 0.045 && !won) {
trailTimer = 0;
if (trailCount < MAX_TRAIL) {
const index = trailCount * 3;
trailArray[index] = ballGroup.position.x;
trailArray[index + 1] = 0.025;
trailArray[index + 2] = ballGroup.position.z;
trailCount++;
} else {
trailArray.copyWithin(0, 3);
const index = (MAX_TRAIL - 1) * 3;
trailArray[index] = ballGroup.position.x;
trailArray[index + 1] = 0.025;
trailArray[index + 2] = ballGroup.position.z;
}
trailGeometry.attributes.position.needsUpdate = true;
trailGeometry.setDrawRange(0, trailCount);
}
// Gate states and floating markers.
checkpoints.forEach((checkpoint, index) => {
checkpoint.flash = Math.max(0, checkpoint.flash - dt * 1.8);
const completed = index < progressIndex;
const active = index === progressIndex && !won;
let intensity = completed ? 0.75 : active ? 2.25 : 0.25;
intensity += checkpoint.flash * 3;
checkpoint.material.emissiveIntensity = intensity;
checkpoint.light.intensity = active ? 4.8 : completed ? 1.4 : 0.7;
const pulse = active ? 1 + Math.sin(elapsed * 4.2) * 0.045 : 1;
checkpoint.ring.scale.setScalar(pulse + checkpoint.flash * 0.2);
checkpoint.marker.position.y = 2.35 + Math.sin(elapsed * 2.5 + index) * 0.12;
checkpoint.marker.rotation.y += dt * 1.5;
checkpoint.marker.rotation.x += dt * 0.7;
});
updateParticles(dt);
// Direct spherical camera update.
const distance = baseCameraDistance * cameraZoom;
const horizontal = Math.sin(cameraPolar) * distance;
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraAzimuth),
cameraTarget.y + Math.cos(cameraPolar) * distance,
cameraTarget.z + horizontal * Math.cos(cameraAzimuth)
);
camera.lookAt(cameraTarget);
renderer.render(scene, camera);
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
camera.aspect = aspect;
camera.updateProjectionMatrix();
// Maintain a useful framing on narrow screens.
const halfFov = THREE.MathUtils.degToRad(camera.fov / 2);
baseCameraDistance = aspect < 1.2
? 13.5 / (Math.tan(halfFov) * aspect)
: 30;
}
window.addEventListener("resize", resize);
resize();
resetGame();
animate();
</script>
</body>
</html>
```