Prompt specification
Build or customize the Three.js 3D scene "Stop a Crate Inside a Target" 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: Stop a Crate Inside a Target
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/stop-a-crate-inside-a-target-x3510
Scene Description Prompt:
Create a short sliding puzzle where the initial push determines stopping distance. Use a simple consistent friction model and display repeated trials from identical starts. Use Three.js from cdnjs in a single HTML file, with visible voxel blocks.
Working Three.js Starter (stop-a-crate-inside-a-target-x3510):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Friction — Sliding Puzzle</title>
<style>
:root {
color-scheme: dark;
--bg: #081018;
--panel: rgba(11, 20, 29, 0.9);
--panel-border: rgba(130, 181, 204, 0.18);
--text: #edf8fb;
--muted: #8ea8b5;
--cyan: #55d8ff;
--green: #49f0a6;
--orange: #ffad42;
--red: #ff6b72;
}
* {
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,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#viewport canvas:active {
cursor: grabbing;
}
.ui {
position: fixed;
inset: 0;
pointer-events: none;
}
.topbar {
position: absolute;
top: 22px;
left: 24px;
right: 24px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 7px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 8px;
height: 8px;
border-radius: 2px;
background: var(--cyan);
box-shadow: 0 0 14px rgba(85, 216, 255, 0.8);
content: "";
}
h1 {
margin: 0;
font-size: clamp(25px, 3vw, 42px);
line-height: 1;
letter-spacing: -0.045em;
}
.subtitle {
max-width: 520px;
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
.stats {
display: grid;
grid-template-columns: repeat(3, minmax(78px, 1fr));
gap: 8px;
pointer-events: auto;
}
.stat {
min-width: 92px;
padding: 10px 12px;
border: 1px solid var(--panel-border);
border-radius: 12px;
background: rgba(10, 18, 27, 0.78);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.18);
backdrop-filter: blur(12px);
}
.stat-label {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.stat-value {
margin-top: 3px;
font-size: 17px;
font-variant-numeric: tabular-nums;
font-weight: 750;
}
.view-button {
position: absolute;
top: 112px;
right: 24px;
padding: 8px 11px;
border: 1px solid var(--panel-border);
border-radius: 9px;
background: rgba(10, 18, 27, 0.75);
color: var(--muted);
font-size: 11px;
cursor: pointer;
pointer-events: auto;
}
.view-button:hover {
color: var(--text);
border-color: rgba(85, 216, 255, 0.45);
}
.dock {
position: absolute;
right: 18px;
bottom: 18px;
left: 18px;
display: grid;
grid-template-columns: 320px minmax(0, 1fr);
gap: 18px;
max-width: 1080px;
max-height: 310px;
margin: 0 auto;
padding: 16px;
border: 1px solid var(--panel-border);
border-radius: 20px;
background: var(--panel);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.42);
backdrop-filter: blur(18px);
pointer-events: auto;
}
.control-panel {
padding-right: 16px;
border-right: 1px solid var(--panel-border);
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 14px;
}
.section-title h2 {
margin: 0;
font-size: 13px;
letter-spacing: 0.02em;
}
.status {
padding: 5px 8px;
border-radius: 999px;
background: rgba(85, 216, 255, 0.1);
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status.success {
color: var(--green);
background: rgba(73, 240, 166, 0.11);
}
.status.fail {
color: var(--red);
background: rgba(255, 107, 114, 0.1);
}
.power-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 7px;
}
.power-row label {
color: var(--muted);
font-size: 11px;
font-weight: 700;
}
#powerValue {
font-size: 23px;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 5px 0 11px;
appearance: none;
border-radius: 99px;
outline: none;
background: linear-gradient(
90deg,
var(--cyan) 0%,
var(--cyan) var(--fill, 40%),
#263a47 var(--fill, 40%),
#263a47 100%
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 18px;
height: 18px;
appearance: none;
border: 3px solid #0d1720;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px var(--cyan), 0 0 15px rgba(85, 216, 255, 0.35);
}
input[type="range"]::-moz-range-thumb {
width: 14px;
height: 14px;
border: 3px solid #0d1720;
border-radius: 50%;
background: var(--cyan);
}
.estimate {
display: flex;
justify-content: space-between;
margin-bottom: 13px;
color: var(--muted);
font-size: 10px;
}
.estimate strong {
color: var(--orange);
font-variant-numeric: tabular-nums;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.primary,
.secondary {
min-height: 38px;
border-radius: 10px;
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition:
transform 0.15s ease,
opacity 0.15s ease,
border-color 0.15s ease;
}
.primary {
grid-column: 1 / -1;
border: 0;
background: linear-gradient(135deg, #63ddff, #38aef0);
color: #07121a;
box-shadow: 0 9px 22px rgba(56, 174, 240, 0.2);
}
.secondary {
border: 1px solid var(--panel-border);
background: rgba(255, 255, 255, 0.035);
color: var(--text);
}
.primary:hover:not(:disabled),
.secondary:hover:not(:disabled) {
transform: translateY(-1px);
}
.secondary:hover:not(:disabled) {
border-color: rgba(85, 216, 255, 0.4);
}
button:disabled {
opacity: 0.45;
cursor: not-allowed;
}
.model-note {
margin-top: 12px;
padding-top: 10px;
border-top: 1px solid var(--panel-border);
color: var(--muted);
font-size: 10px;
line-height: 1.45;
}
.model-note code {
color: #bcefff;
font-size: 10px;
}
.history-panel {
min-width: 0;
}
.history-header {
display: grid;
grid-template-columns: 34px 52px 70px minmax(100px, 1fr) 66px;
gap: 8px;
align-items: center;
padding: 0 5px 7px;
color: #68818f;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#historyRows {
max-height: 214px;
overflow-y: auto;
scrollbar-width: thin;
scrollbar-color: #2b4351 transparent;
}
.trial-row {
display: grid;
grid-template-columns: 34px 52px 70px minmax(100px, 1fr) 66px;
gap: 8px;
align-items: center;
min-height: 43px;
padding: 5px;
border-top: 1px solid rgba(130, 181, 204, 0.09);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.trial-number {
color: var(--muted);
}
.trial-track {
position: relative;
height: 16px;
border-radius: 4px;
background:
repeating-linear-gradient(
90deg,
rgba(255, 255, 255, 0.045) 0,
rgba(255, 255, 255, 0.045) 1px,
transparent 1px,
transparent 10%
),
rgba(255, 255, 255, 0.025);
}
.goal-band {
position: absolute;
top: 2px;
bottom: 2px;
border-radius: 3px;
background: rgba(73, 240, 166, 0.18);
border: 1px solid rgba(73, 240, 166, 0.48);
}
.start-dot {
position: absolute;
top: 50%;
left: 4%;
width: 5px;
height: 5px;
border-radius: 50%;
background: var(--cyan);
transform: translateY(-50%);
}
.stop-dot {
position: absolute;
top: 50%;
width: 9px;
height: 9px;
border: 2px solid #07121a;
border-radius: 2px;
background: var(--orange);
box-shadow: 0 0 8px rgba(255, 173, 66, 0.35);
transform: translate(-50%, -50%) rotate(45deg);
}
.trial-result {
font-size: 9px;
font-weight: 800;
text-align: right;
text-transform: uppercase;
}
.trial-result.win {
color: var(--green);
}
.trial-result.miss {
color: var(--red);
}
.empty-history {
display: grid;
min-height: 150px;
place-items: center;
color: var(--muted);
font-size: 11px;
text-align: center;
}
.legend {
display: flex;
gap: 14px;
margin-top: 8px;
color: #78909d;
font-size: 9px;
}
.legend span::before {
display: inline-block;
width: 7px;
height: 7px;
margin-right: 5px;
border-radius: 2px;
vertical-align: 1px;
background: var(--cyan);
content: "";
}
.legend .goal-key::before {
background: var(--green);
}
.legend .stop-key::before {
background: var(--orange);
}
.world-label {
position: fixed;
z-index: 2;
pointer-events: none;
transform: translate(-50%, -50%);
white-space: nowrap;
}
.start-label,
.goal-label {
padding: 5px 8px;
border: 1px solid rgba(85, 216, 255, 0.3);
border-radius: 6px;
background: rgba(7, 17, 25, 0.78);
color: var(--cyan);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.12em;
box-shadow: 0 7px 20px rgba(0, 0, 0, 0.22);
}
.goal-label {
border-color: rgba(73, 240, 166, 0.38);
color: var(--green);
}
.ruler-label {
color: rgba(176, 203, 214, 0.55);
font-size: 9px;
font-weight: 700;
text-shadow: 0 2px 5px #000;
}
#toast {
position: fixed;
top: 25px;
left: 50%;
z-index: 10;
min-width: 260px;
max-width: calc(100% - 32px);
padding: 12px 18px;
border: 1px solid rgba(73, 240, 166, 0.35);
border-radius: 12px;
background: rgba(9, 22, 28, 0.94);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.38);
opacity: 0;
transform: translate(-50%, -18px);
transition:
opacity 0.2s ease,
transform 0.2s ease;
pointer-events: none;
text-align: center;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
#toast.win {
border-color: rgba(73, 240, 166, 0.55);
}
#toast.miss {
border-color: rgba(255, 107, 114, 0.5);
}
.toast-title {
font-size: 13px;
font-weight: 850;
}
.toast-detail {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
background: var(--bg);
color: var(--cyan);
font-size: 12px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
transition: opacity 0.4s ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 760px) {
.topbar {
top: 14px;
left: 14px;
right: 14px;
}
.subtitle {
max-width: 310px;
font-size: 11px;
}
.stats {
grid-template-columns: repeat(3, 68px);
gap: 4px;
}
.stat {
min-width: 0;
padding: 8px;
}
.stat-value {
font-size: 13px;
}
.view-button {
top: 88px;
right: 14px;
}
.dock {
right: 10px;
bottom: 10px;
left: 10px;
grid-template-columns: 1fr;
gap: 12px;
max-height: 47vh;
padding: 13px;
overflow-y: auto;
}
.control-panel {
padding-right: 0;
padding-bottom: 12px;
border-right: 0;
border-bottom: 1px solid var(--panel-border);
}
#historyRows {
max-height: 160px;
}
}
@media (max-width: 480px) {
.stats {
position: absolute;
top: 91px;
right: 0;
}
.subtitle {
max-width: 250px;
}
.view-button {
top: 145px;
}
.history-header,
.trial-row {
grid-template-columns: 28px 45px 61px minmax(80px, 1fr) 54px;
gap: 5px;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div class="ui">
<div class="topbar">
<div>
<div class="eyebrow">Voxel friction lab</div>
<h1>Push. Slide. Stop.</h1>
<p class="subtitle">
Choose an initial push and try to stop inside the green zone.
Every trial begins from the exact same launch tile.
</p>
</div>
<div class="stats">
<div class="stat">
<div class="stat-label">Trials</div>
<div class="stat-value" id="attemptCount">0</div>
</div>
<div class="stat">
<div class="stat-label">Last stop</div>
<div class="stat-value" id="lastStop">—</div>
</div>
<div class="stat">
<div class="stat-label">Best error</div>
<div class="stat-value" id="bestError">—</div>
</div>
</div>
</div>
<button class="view-button" id="resetView" type="button">
Reset camera
</button>
<section class="dock">
<div class="control-panel">
<div class="section-title">
<h2>Initial push</h2>
<div class="status" id="status">Ready</div>
</div>
<div class="power-row">
<label for="power">Launch velocity</label>
<div id="powerValue">6.0 m/s</div>
</div>
<input
id="power"
type="range"
min="3"
max="9.5"
step="0.1"
value="6"
aria-label="Initial launch velocity"
>
<div class="estimate">
<span>Constant-friction prediction</span>
<strong id="estimate">5.25 m stop</strong>
</div>
<div class="button-row">
<button class="primary" id="launch" type="button">
Launch trial
</button>
<button class="secondary" id="clearTrials" type="button">
Clear trials
</button>
<button class="secondary" id="newGoal" type="button">
New goal
</button>
</div>
<div class="model-note">
Sliding friction only:
<code>a = μg</code>, with <code>μ = 0.35</code> and
<code>g = 9.81 m/s²</code>.
The model uses <code>d = v₀² / (2μg)</code>.
</div>
</div>
<div class="history-panel">
<div class="section-title">
<h2>Repeated trials</h2>
<span style="color:var(--muted);font-size:10px">
Same start · same friction
</span>
</div>
<div class="history-header">
<span>Trial</span>
<span>Push</span>
<span>Stop</span>
<span>Distance lane</span>
<span>Result</span>
</div>
<div id="historyRows">
<div class="empty-history">
Launch a trial to plot its stopping distance.
</div>
</div>
<div class="legend">
<span>Start</span>
<span class="goal-key">Goal zone</span>
<span class="stop-key">Stopping point</span>
</div>
</div>
</section>
</div>
<div id="startLabel" class="world-label start-label">START · 0 m</div>
<div id="goalLabel" class="world-label goal-label">GOAL ZONE</div>
<div id="toast">
<div class="toast-title" id="toastTitle"></div>
<div class="toast-detail" id="toastDetail"></div>
</div>
<div id="loading">Loading voxel arena…</div>
<noscript>This puzzle requires JavaScript.</noscript>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
// ------------------------------------------------------------
// Model and puzzle constants
// ------------------------------------------------------------
const GRAVITY = 9.81;
const MU = 0.35;
const DECELERATION = MU * GRAVITY;
const START_X = -11.5;
const GOAL_TOLERANCE = 1.0;
const MAX_DISTANCE = 13.2;
let goalDistance = randomGoalDistance();
let phase = "ready";
let attempt = 0;
let trialHistory = [];
let activeTrial = null;
let toastTimer = 0;
const palette = [
0x55d8ff,
0xffad42,
0xa987ff,
0x49f0a6,
0xff6b91,
0xf7e06c
];
function randomGoalDistance() {
return Math.round((4 + Math.random() * 7.2) * 10) / 10;
}
// ------------------------------------------------------------
// Renderer and scene
// ------------------------------------------------------------
const viewport = $("viewport");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x081018);
scene.fog = new THREE.Fog(0x081018, 24, 58);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(-3.5, 0, 0);
let cameraRadius = 29;
let cameraTheta = 0;
let cameraPhi = 1.03;
function updateCamera() {
const aspect = window.innerWidth / window.innerHeight;
const responsiveMultiplier =
aspect < 0.85 ? 1.42 : aspect < 1.25 ? 1.18 : 1;
const radius = cameraRadius * responsiveMultiplier;
const horizontal = radius * Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + horizontal * Math.sin(cameraTheta),
cameraTarget.y + radius * Math.cos(cameraPhi),
cameraTarget.z + horizontal * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xbeeaff, 0x17232c, 2.2);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffffff, 3.1);
sun.position.set(-7, 18, 10);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -23;
sun.shadow.camera.right = 23;
sun.shadow.camera.top = 17;
sun.shadow.camera.bottom = -17;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 55;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x55d8ff, 1.3);
rimLight.position.set(12, 7, -13);
scene.add(rimLight);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x111d27,
roughness: 0.95,
metalness: 0.05
});
const ground = new THREE.Mesh(
new THREE.BoxGeometry(34, 0.3, 12),
groundMaterial
);
ground.position.set(-3.5, -0.22, 0);
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(
34,
34,
0x426273,
0x203746
);
grid.position.set(-3.5, -0.055, 0);
grid.scale.z = 12 / 34;
grid.material.transparent = true;
grid.material.opacity = 0.25;
scene.add(grid);
const runway = new THREE.Mesh(
new THREE.BoxGeometry(25, 0.055, 3.5),
new THREE.MeshStandardMaterial({
color: 0x172936,
roughness: 0.9,
transparent: true,
opacity: 0.92
})
);
runway.position.set(0.25, -0.02, 0);
runway.receiveShadow = true;
scene.add(runway);
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x477184,
emissive: 0x102b38,
emissiveIntensity: 0.5,
roughness: 0.8
});
for (const z of [-1.78, 1.78]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(25, 0.055, 0.065),
railMaterial
);
rail.position.set(0.25, 0.02, z);
scene.add(rail);
}
// One-meter tick marks.
const tickMaterial = new THREE.MeshStandardMaterial({
color: 0x3e6679,
roughness: 0.8
});
for (let meter = 0; meter <= 13; meter++) {
const tick = new THREE.Mesh(
new THREE.BoxGeometry(0.055, 0.035, 0.28),
tickMaterial
);
tick.position.set(START_X + meter, 0.025, -1.52);
scene.add(tick);
}
// Decorative voxel stacks outside the sliding lane.
const voxelColors = [
0x173344,
0x1d4153,
0x21495b,
0x163440
];
let seed = 931;
function seededRandom() {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
}
for (let x = -16; x <= 11; x += 3.15) {
for (const z of [-4.35, 4.35]) {
const count = 1 + Math.floor(seededRandom() * 4);
const material = new THREE.MeshStandardMaterial({
color: voxelColors[Math.floor(seededRandom() * voxelColors.length)],
roughness: 0.85,
metalness: 0.08
});
for (let level = 0; level < count; level++) {
const block = new THREE.Mesh(
new THREE.BoxGeometry(0.74, 0.46, 0.74),
material
);
block.position.set(
x + (seededRandom() - 0.5) * 0.35,
0.08 + level * 0.47,
z + (seededRandom() - 0.5) * 0.25
);
block.rotation.y = (seededRandom() - 0.5) * 0.16;
block.castShadow = true;
block.receiveShadow = true;
scene.add(block);
}
}
}
// ------------------------------------------------------------
// Start gate
// ------------------------------------------------------------
const startGroup = new THREE.Group();
startGroup.position.x = START_X;
scene.add(startGroup);
const startMaterial = new THREE.MeshStandardMaterial({
color: 0x2387ae,
emissive: 0x0b4968,
emissiveIntensity: 0.65,
roughness: 0.62
});
for (const z of [-1.38, 1.38]) {
for (let level = 0; level < 3; level++) {
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.28, 0.32, 0.28),
startMaterial
);
cube.position.set(0, 0.18 + level * 0.34, z);
cube.castShadow = true;
startGroup.add(cube);
}
}
for (let i = -4; i <= 4; i++) {
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.25, 0.25),
startMaterial
);
cube.position.set(0, 1.15, i * 0.31);
cube.castShadow = true;
startGroup.add(cube);
}
// ------------------------------------------------------------
// Goal zone and gate
// ------------------------------------------------------------
const goalGroup = new THREE.Group();
scene.add(goalGroup);
const goalCubeMaterial = new THREE.MeshStandardMaterial({
color: 0x49f0a6,
emissive: 0x0b6c48,
emissiveIntensity: 0.55,
roughness: 0.55
});
const goalZoneMaterial = new THREE.MeshBasicMaterial({
color: 0x49f0a6,
transparent: true,
opacity: 0.14,
depthWrite: false
});
function rebuildGoal() {
goalGroup.clear();
goalGroup.position.x = START_X + goalDistance;
const zone = new THREE.Mesh(
new THREE.BoxGeometry(GOAL_TOLERANCE * 2, 0.035, 2.45),
goalZoneMaterial
);
zone.position.y = 0.035;
goalGroup.add(zone);
for (const z of [-1.38, 1.38]) {
for (let level = 0; level < 5; level++) {
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.28, 0.32, 0.28),
goalCubeMaterial
);
cube.position.set(0, 0.18 + level * 0.34, z);
cube.castShadow = true;
goalGroup.add(cube);
}
}
for (let i = -4; i <= 4; i++) {
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.25, 0.25, 0.25),
goalCubeMaterial
);
cube.position.set(0, 1.86, i * 0.31);
cube.castShadow = true;
goalGroup.add(cube);
}
}
rebuildGoal();
// ------------------------------------------------------------
// Moving voxel block
// ------------------------------------------------------------
const mover = new THREE.Group();
mover.position.x = START_X;
scene.add(mover);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0xf08b36,
roughness: 0.65,
metalness: 0.05
});
const frontMaterial = new THREE.MeshStandardMaterial({
color: 0xffbd54,
emissive: 0x6a3200,
emissiveIntensity: 0.22,
roughness: 0.55
});
const topMaterial = new THREE.MeshStandardMaterial({
color: 0xffd477,
roughness: 0.52
});
for (let ix = -1; ix <= 1; ix++) {
for (let iz = -1; iz <= 1; iz++) {
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.42, 0.42),
ix === 1 ? frontMaterial : bodyMaterial
);
cube.position.set(ix * 0.43, 0.23, iz * 0.43);
cube.castShadow = true;
cube.receiveShadow = true;
mover.add(cube);
}
}
const topCube = new THREE.Mesh(
new THREE.BoxGeometry(0.42, 0.42, 0.42),
topMaterial
);
topCube.position.set(0, 0.65, 0);
topCube.castShadow = true;
mover.add(topCube);
// Trial trails and persistent stopping markers.
const trailGroup = new THREE.Group();
const markerGroup = new THREE.Group();
scene.add(trailGroup, markerGroup);
const crumbGeometry = new THREE.BoxGeometry(0.12, 0.12, 0.12);
const markerGeometry = new THREE.BoxGeometry(0.34, 0.34, 0.34);
const markerMaterials = palette.map(
(color) =>
new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.2,
roughness: 0.6
})
);
// ------------------------------------------------------------
// DOM labels projected from the 3D scene
// ------------------------------------------------------------
const rulerLabels = [];
for (let meter = 2; meter <= 12; meter += 2) {
const label = document.createElement("div");
label.className = "world-label ruler-label";
label.textContent = `${meter} m`;
document.body.appendChild(label);
rulerLabels.push({
element: label,
position: new THREE.Vector3(START_X + meter, 0.18, -2.18)
});
}
const startLabelPosition = new THREE.Vector3(
START_X,
1.55,
-1.55
);
const goalLabelPosition = new THREE.Vector3(
START_X + goalDistance,
2.35,
-1.45
);
const projected = new THREE.Vector3();
function projectLabel(element, position) {
projected.copy(position).project(camera);
if (projected.z < -1 || projected.z > 1) {
element.style.display = "none";
return;
}
element.style.display = "";
element.style.left = `${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-projected.y * 0.5 + 0.5) * window.innerHeight}px`;
}
// ------------------------------------------------------------
// Puzzle UI
// ------------------------------------------------------------
function predictedDistance(velocity) {
return (velocity * velocity) / (2 * DECELERATION);
}
function updatePowerReadout() {
const velocity = Number($("power").value);
const percent =
((velocity - 3) / (9.5 - 3)) * 100;
$("power").style.setProperty("--fill", `${percent}%`);
$("powerValue").textContent = `${velocity.toFixed(1)} m/s`;
$("estimate").textContent =
`${predictedDistance(velocity).toFixed(2)} m stop`;
}
$("power").addEventListener("input", updatePowerReadout);
updatePowerReadout();
function setStatus(text, type = "") {
const status = $("status");
status.textContent = text;
status.className = `status ${type}`.trim();
}
function showToast(title, detail, type = "") {
const toast = $("toast");
$("toastTitle").textContent = title;
$("toastDetail").textContent = detail;
toast.className = `show ${type}`.trim();
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.className = type;
}, 2600);
}
function setControlsRunning(running) {
$("power").disabled = running;
$("launch").disabled = running;
$("clearTrials").disabled = running;
$("newGoal").disabled = running;
$("launch").textContent = running ? "Sliding…" : "Launch trial";
}
function addTrailCrumb(x, color) {
const material = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.42,
depthWrite: false
});
const crumb = new THREE.Mesh(crumbGeometry, material);
crumb.position.set(x, 0.075, 0);
trailGroup.add(crumb);
}
function launchTrial() {
if (phase === "running") return;
attempt++;
phase = "running";
setControlsRunning(true);
setStatus("Sliding");
const velocity = Number($("power").value);
const color = palette[(attempt - 1) % palette.length];
activeTrial = {
velocity,
color,
elapsed: 0,
stopTime: velocity / DECELERATION,
lastCrumbX: START_X
};
mover.position.x = START_X;
trailGroup.clear();
}
function finishTrial() {
phase = "stopped";
const velocity = activeTrial.velocity;
const distance = predictedDistance(velocity);
const error = distance - goalDistance;
const absoluteError = Math.abs(error);
const success = absoluteError <= GOAL_TOLERANCE;
mover.position.x = START_X + distance;
const marker = new THREE.Mesh(
markerGeometry,
markerMaterials[(attempt - 1) % markerMaterials.length]
);
marker.position.set(
START_X + distance,
0.17,
2.45 + ((attempt - 1) % 3) * 0.48
);
marker.castShadow = true;
markerGroup.add(marker);
trialHistory.push({
attempt,
velocity,
distance,
error,
success
});
updateHistory();
setControlsRunning(false);
if (success) {
setStatus("Solved", "success");
showToast(
"Target locked in!",
`${attempt} trial${attempt === 1 ? "" : "s"} · ${distance.toFixed(2)} m stop`,
"win"
);
} else {
const direction = error < 0 ? "Short by" : "Overshot by";
setStatus("Try again", "fail");
showToast(
`${direction} ${absoluteError.toFixed(2)} m`,
"The next trial resets to the same launch tile.",
"miss"
);
}
}
function lanePercent(distance) {
return 4 + (distance / MAX_DISTANCE) * 92;
}
function updateHistory() {
$("attemptCount").textContent = attempt;
$("lastStop").textContent =
trialHistory.length > 0
? `${trialHistory[trialHistory.length - 1].distance.toFixed(2)} m`
: "—";
if (trialHistory.length === 0) {
$("bestError").textContent = "—";
$("historyRows").innerHTML =
'<div class="empty-history">Launch a trial to plot its stopping distance.</div>';
return;
}
const bestError = Math.min(
...trialHistory.map((trial) => Math.abs(trial.error))
);
$("bestError").textContent = `${bestError.toFixed(2)} m`;
const bandWidth =
((GOAL_TOLERANCE * 2) / MAX_DISTANCE) * 92;
const bandLeft = lanePercent(goalDistance) - bandWidth / 2;
const rows = trialHistory
.map(
(trial) => `
<div class="trial-row">
<div class="trial-number">#${trial.attempt}</div>
<div>${trial.velocity.toFixed(1)} m/s</div>
<div>${trial.distance.toFixed(2)} m</div>
<div class="trial-track">
<div
class="goal-band"
style="left:${bandLeft}%;width:${bandWidth}%"
></div>
<div class="start-dot"></div>
<div
class="stop-dot"
style="left:${lanePercent(trial.distance)}%"
></div>
</div>
<div class="trial-result ${trial.success ? "win" : "miss"}">
${trial.success ? "In zone" : `${Math.abs(trial.error).toFixed(2)} m off`}
</div>
</div>
`
)
.join("");
$("historyRows").innerHTML = rows;
$("historyRows").scrollTop = $("historyRows").scrollHeight;
}
function clearTrials() {
phase = "ready";
attempt = 0;
trialHistory = [];
activeTrial = null;
mover.position.x = START_X;
trailGroup.clear();
markerGroup.clear();
updateHistory();
setControlsRunning(false);
setStatus("Ready");
}
function newGoal() {
clearTrials();
goalDistance = randomGoalDistance();
rebuildGoal();
goalLabelPosition.set(
START_X + goalDistance,
2.35,
-1.45
);
setStatus("New goal");
showToast(
"New goal placed",
"Every trial still starts from the same launch tile.",
""
);
}
$("launch").addEventListener("click", launchTrial);
$("clearTrials").addEventListener("click", clearTrials);
$("newGoal").addEventListener("click", newGoal);
document.addEventListener("keydown", (event) => {
const tag = event.target?.tagName;
if (
event.code === "Space" &&
tag !== "INPUT" &&
tag !== "BUTTON"
) {
event.preventDefault();
launchTrial();
}
});
// ------------------------------------------------------------
// Direct camera controls — no external controls addon
// ------------------------------------------------------------
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 deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
cameraTheta -= deltaX * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi + deltaY * 0.004,
0.55,
1.35
);
updateCamera();
});
function stopDragging() {
dragging = false;
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.018,
18,
44
);
updateCamera();
},
{ passive: false }
);
function resetCamera() {
cameraRadius = 29;
cameraTheta = 0;
cameraPhi = 1.03;
updateCamera();
}
$("resetView").addEventListener("click", resetCamera);
renderer.domElement.addEventListener("dblclick", resetCamera);
// ------------------------------------------------------------
// Resize and animation
// ------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
updateCamera();
});
const clock = new THREE.Clock();
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
if (phase === "running" && activeTrial) {
activeTrial.elapsed += delta;
const time = Math.min(
activeTrial.elapsed,
activeTrial.stopTime
);
// Analytic constant-acceleration motion.
const x =
START_X +
activeTrial.velocity * time -
0.5 * DECELERATION * time * time;
mover.position.x = x;
if (x - activeTrial.lastCrumbX >= 0.28) {
addTrailCrumb(x, activeTrial.color);
activeTrial.lastCrumbX = x;
}
if (activeTrial.elapsed >= activeTrial.stopTime) {
finishTrial();
}
}
const pulse = 0.5 + Math.sin(performance.now() * 0.003) * 0.16;
goalCubeMaterial.emissiveIntensity = pulse;
goalZoneMaterial.opacity = 0.12 + pulse * 0.06;
projectLabel($("startLabel"), startLabelPosition);
projectLabel($("goalLabel"), goalLabelPosition);
for (const label of rulerLabels) {
projectLabel(label.element, label.position);
}
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
requestAnimationFrame(() => {
$("loading").classList.add("hidden");
setTimeout(() => $("loading").remove(), 450);
});
</script>
</body>
</html>
```