Prompt specification
Build or customize the Three.js 3D scene "Gentle Roll Toward a Target Ball" 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: Gentle Roll Toward a Target Ball
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/gentle-roll-toward-a-target-ball-x3662
Scene Description Prompt:
Roll a voxel ball toward a jack with adjustable release speed and stated deceleration; compare final separation. One HTML file using Three.js from cdnjs.
Working Three.js Starter (gentle-roll-toward-a-target-ball-x3662):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Voxel Roll Lab</title>
<style>
:root {
color-scheme: light;
--ink: #18312d;
--muted: #60736e;
--panel: rgba(250, 252, 248, 0.92);
--line: rgba(28, 67, 59, 0.14);
--green: #19766a;
--green-dark: #10554d;
--gold: #f2b84b;
--red: #d94d45;
--shadow: 0 18px 50px rgba(27, 59, 52, 0.17);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--ink);
background: #dce8e2;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene canvas:active {
cursor: grabbing;
}
.brand {
position: fixed;
top: 22px;
left: 24px;
z-index: 2;
pointer-events: none;
max-width: 440px;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
padding: 7px 10px;
border: 1px solid rgba(25, 118, 106, 0.2);
border-radius: 999px;
background: rgba(250, 252, 248, 0.78);
color: var(--green-dark);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
backdrop-filter: blur(12px);
}
.eyebrow::before {
width: 7px;
height: 7px;
border-radius: 2px;
background: var(--gold);
content: "";
box-shadow: 0 0 0 3px rgba(242, 184, 75, 0.2);
}
.brand h1 {
margin: 0;
font-size: clamp(28px, 4vw, 54px);
line-height: 0.96;
letter-spacing: -0.055em;
text-shadow: 0 2px 20px rgba(255, 255, 255, 0.45);
}
.brand p {
max-width: 380px;
margin: 12px 0 0;
color: #49615c;
font-size: 14px;
line-height: 1.5;
}
.panel {
position: fixed;
z-index: 3;
top: 18px;
right: 18px;
width: 370px;
max-height: calc(100vh - 36px);
overflow: auto;
padding: 20px;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 22px;
background: var(--panel);
box-shadow: var(--shadow);
backdrop-filter: blur(20px) saturate(1.15);
scrollbar-width: thin;
scrollbar-color: rgba(25, 118, 106, 0.3) transparent;
}
.panel-heading {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 16px;
margin-bottom: 18px;
}
.panel-heading h2 {
margin: 0;
font-size: 20px;
letter-spacing: -0.025em;
}
.panel-heading p {
margin: 5px 0 0;
color: var(--muted);
font-size: 12px;
line-height: 1.4;
}
.badge {
flex: 0 0 auto;
padding: 6px 9px;
border-radius: 999px;
background: rgba(25, 118, 106, 0.1);
color: var(--green-dark);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.control {
margin-top: 17px;
}
.control-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 9px;
}
.control label {
font-size: 12px;
font-weight: 750;
}
output {
color: var(--green-dark);
font-size: 13px;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 0;
border-radius: 999px;
outline: none;
background:
linear-gradient(
90deg,
var(--green) 0%,
var(--green) var(--fill, 50%),
rgba(25, 118, 106, 0.14) var(--fill, 50%),
rgba(25, 118, 106, 0.14) 100%
);
appearance: none;
-webkit-appearance: none;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 18px;
height: 18px;
border: 3px solid white;
border-radius: 50%;
background: var(--green);
box-shadow: 0 2px 8px rgba(15, 69, 61, 0.25);
appearance: none;
-webkit-appearance: none;
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 3px solid white;
border-radius: 50%;
background: var(--green);
box-shadow: 0 2px 8px rgba(15, 69, 61, 0.25);
}
.range-ends {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: #82908d;
font-size: 10px;
}
.model-note {
margin-top: 18px;
padding: 12px 13px;
border: 1px solid rgba(25, 118, 106, 0.12);
border-radius: 13px;
background: rgba(25, 118, 106, 0.055);
color: #4e6560;
font-size: 11px;
line-height: 1.5;
}
.model-note strong {
display: block;
margin-bottom: 3px;
color: var(--green-dark);
font-size: 11px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.model-note code {
color: #285c54;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 16px;
}
.metric {
min-height: 76px;
padding: 12px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.54);
}
.metric.wide {
grid-column: 1 / -1;
}
.metric span {
display: block;
margin-bottom: 7px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.045em;
text-transform: uppercase;
}
.metric strong {
display: block;
font-size: 21px;
letter-spacing: -0.04em;
font-variant-numeric: tabular-nums;
}
.metric small {
display: block;
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.status {
display: flex;
align-items: center;
gap: 9px;
margin-top: 13px;
padding: 10px 12px;
border-radius: 11px;
background: #e8f1ed;
color: var(--green-dark);
font-size: 11px;
font-weight: 750;
line-height: 1.35;
}
.status::before {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 0 4px rgba(25, 118, 106, 0.11);
content: "";
}
.status.hit {
background: #fff0ed;
color: #8c332d;
}
.status.hit::before {
background: var(--red);
box-shadow: 0 0 0 4px rgba(217, 77, 69, 0.12);
}
.buttons {
display: grid;
grid-template-columns: 1.5fr 1fr;
gap: 9px;
margin-top: 15px;
}
button {
min-height: 44px;
border: 0;
border-radius: 12px;
cursor: pointer;
font-size: 12px;
font-weight: 800;
transition:
transform 120ms ease,
opacity 120ms ease,
background 120ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
}
button:active:not(:disabled) {
transform: translateY(0);
}
button:disabled {
cursor: wait;
opacity: 0.55;
}
.primary {
background: var(--green);
color: white;
box-shadow: 0 7px 18px rgba(25, 118, 106, 0.2);
}
.primary:hover:not(:disabled) {
background: var(--green-dark);
}
.secondary {
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.72);
color: var(--ink);
}
.history {
margin-top: 20px;
padding-top: 16px;
border-top: 1px solid var(--line);
}
.history-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
}
.history-heading h3 {
margin: 0;
font-size: 13px;
}
.history-heading span {
color: var(--muted);
font-size: 10px;
}
.table-wrap {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
font-size: 10px;
font-variant-numeric: tabular-nums;
}
th {
padding: 7px 5px;
border-bottom: 1px solid var(--line);
color: var(--muted);
font-size: 9px;
letter-spacing: 0.04em;
text-align: right;
text-transform: uppercase;
}
td {
padding: 8px 5px;
border-bottom: 1px solid rgba(28, 67, 59, 0.07);
text-align: right;
white-space: nowrap;
}
th:first-child,
td:first-child {
text-align: left;
}
tbody tr:last-child td {
border-bottom: 0;
}
.result-hit {
color: var(--red);
font-weight: 800;
}
.result-miss {
color: var(--green-dark);
font-weight: 800;
}
.empty-history {
padding: 10px 0;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
.camera-hint {
position: fixed;
z-index: 2;
left: 24px;
bottom: 20px;
padding: 9px 12px;
border: 1px solid rgba(255, 255, 255, 0.58);
border-radius: 999px;
background: rgba(250, 252, 248, 0.7);
color: #58716b;
font-size: 10px;
font-weight: 700;
pointer-events: none;
backdrop-filter: blur(10px);
}
@media (max-width: 760px) {
.brand {
top: 14px;
left: 14px;
}
.brand h1 {
font-size: 31px;
}
.brand p {
display: none;
}
.panel {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 58vh;
padding: 16px;
border-radius: 18px;
}
.camera-hint {
display: none;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive voxel ball and jack simulation"></div>
<header class="brand">
<div class="eyebrow">Physics playground</div>
<h1>Voxel Roll Lab</h1>
<p>
Release a rolling voxel ball, apply constant deceleration, and compare
its final surface-to-surface separation from the jack.
</p>
</header>
<aside class="panel">
<div class="panel-heading">
<div>
<h2>Release setup</h2>
<p>Adjust the inputs, then release the ball.</p>
</div>
<div class="badge">Constant a</div>
</div>
<div class="control">
<div class="control-row">
<label for="speed">Release speed</label>
<output id="speedValue" for="speed">4.8 m/s</output>
</div>
<input id="speed" type="range" min="1" max="10" step="0.1" value="4.8">
<div class="range-ends">
<span>1 m/s</span>
<span>10 m/s</span>
</div>
</div>
<div class="control">
<div class="control-row">
<label for="deceleration">Constant deceleration</label>
<output id="decelerationValue" for="deceleration">1.20 m/s²</output>
</div>
<input
id="deceleration"
type="range"
min="0.1"
max="3"
step="0.05"
value="1.2"
>
<div class="range-ends">
<span>0.10 m/s²</span>
<span>3.00 m/s²</span>
</div>
</div>
<div class="control">
<div class="control-row">
<label for="distance">Release-to-jack distance</label>
<output id="distanceValue" for="distance">12.0 m</output>
</div>
<input
id="distance"
type="range"
min="4"
max="24"
step="0.5"
value="12"
>
<div class="range-ends">
<span>4 m</span>
<span>24 m</span>
</div>
</div>
<div class="model-note">
<strong>Stated motion model</strong>
After release,
<code>v(t) = max(0, v₀ − at)</code>
and the predicted stopping distance is
<code>s = v₀² / (2a)</code>.
Deceleration continues at the stated constant rate until the ball stops.
</div>
<div class="metrics">
<div class="metric">
<span>Stopping distance</span>
<strong id="stopMetric">9.60 m</strong>
<small>before contact</small>
</div>
<div class="metric">
<span>Projected edge gap</span>
<strong id="projectedMetric">0.98 m</strong>
<small>surface to surface</small>
</div>
<div class="metric">
<span>Simulated final gap</span>
<strong id="actualMetric">—</strong>
<small id="actualDetail">not released yet</small>
</div>
<div class="metric">
<span>Prediction error</span>
<strong id="errorMetric">—</strong>
<small>simulated minus projected</small>
</div>
<div class="metric wide">
<span>Final center-to-center separation</span>
<strong id="centerMetric">2.40 m</strong>
<small>A final edge gap of zero means the ball and jack touch.</small>
</div>
</div>
<div id="status" class="status" role="status" aria-live="polite">
Ready to release.
</div>
<div class="buttons">
<button id="release" class="primary" type="button">Release ball</button>
<button id="reset" class="secondary" type="button">Reset scene</button>
</div>
<section class="history">
<div class="history-heading">
<h3>Run comparison</h3>
<span id="historyCount">0 completed runs</span>
</div>
<div id="emptyHistory" class="empty-history">
Complete a roll to compare its final separation with earlier runs.
</div>
<div id="tableWrap" class="table-wrap" hidden>
<table>
<thead>
<tr>
<th>Release</th>
<th>Decel.</th>
<th>Stop</th>
<th>Final gap</th>
<th>Result</th>
</tr>
</thead>
<tbody id="historyBody"></tbody>
</table>
</div>
</section>
</aside>
<div class="camera-hint">Drag to orbit · Scroll to zoom · Space to release</div>
<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);
const sceneHost = $("scene");
const scene = new THREE.Scene();
const backgroundColor = 0xdce8e2;
scene.background = new THREE.Color(backgroundColor);
scene.fog = new THREE.Fog(backgroundColor, 42, 92);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
160
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
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.05;
sceneHost.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(
0xf5fff8,
0x6d8176,
2.25
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff4da, 3.1);
sun.position.set(-10, 19, 11);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -30;
sun.shadow.camera.right = 30;
sun.shadow.camera.top = 24;
sun.shadow.camera.bottom = -24;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 70;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xb9ddff, 1.0);
fill.position.set(12, 8, -13);
scene.add(fill);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0xcddbd4,
roughness: 1,
metalness: 0
});
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(76, 38),
groundMaterial
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.065;
ground.receiveShadow = true;
scene.add(ground);
const laneMaterial = new THREE.MeshStandardMaterial({
color: 0xf1f3e9,
roughness: 0.94,
metalness: 0
});
const lane = new THREE.Mesh(
new THREE.BoxGeometry(54, 0.07, 3.6),
laneMaterial
);
lane.position.y = -0.025;
lane.receiveShadow = true;
scene.add(lane);
const grid = new THREE.GridHelper(54, 54, 0x6f8f85, 0x9eb5ad);
grid.position.y = 0.018;
grid.material.transparent = true;
grid.material.opacity = 0.28;
scene.add(grid);
const railMaterial = new THREE.MeshStandardMaterial({
color: 0x779d91,
roughness: 0.8
});
for (const z of [-1.9, 1.9]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(54, 0.12, 0.09),
railMaterial
);
rail.position.set(0, 0.065, z);
rail.castShadow = true;
rail.receiveShadow = true;
scene.add(rail);
}
const BALL_RADIUS = 0.9;
const JACK_RADIUS = 0.52;
const CONTACT_DISTANCE = BALL_RADIUS + JACK_RADIUS;
function createTextSprite(text, color = "#274c45") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(247, 250, 244, 0.86)";
context.fillRect(0, 8, canvas.width, canvas.height - 16);
context.fillStyle = color;
context.font = "800 50px 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,
depthWrite: false
})
);
sprite.scale.set(2.5, 0.625, 1);
return sprite;
}
for (let x = -20; x <= 20; x += 5) {
const label = createTextSprite(`${x > 0 ? "+" : ""}${x} m`, "#61766f");
label.position.set(x, 0.34, 2.55);
scene.add(label);
const line = new THREE.Mesh(
new THREE.BoxGeometry(0.035, 0.018, 3.55),
new THREE.MeshBasicMaterial({
color: x === 0 ? 0x3b776b : 0x9bb1a9,
transparent: true,
opacity: x === 0 ? 0.7 : 0.42
})
);
line.position.set(x, 0.045, 0);
scene.add(line);
}
const releaseLabel = createTextSprite("RELEASE", "#8a6217");
releaseLabel.position.set(0, 0.4, 2.55);
scene.add(releaseLabel);
const jackLabel = createTextSprite("JACK", "#9b3f39");
jackLabel.position.set(0, 0.42, 2.55);
scene.add(jackLabel);
function createRing(innerRadius, outerRadius, color) {
const ring = new THREE.Mesh(
new THREE.RingGeometry(innerRadius, outerRadius, 40),
new THREE.MeshBasicMaterial({
color,
side: THREE.DoubleSide,
transparent: true,
opacity: 0.72
})
);
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.052;
return ring;
}
const releaseRing = createRing(0.95, 1.08, 0xe0a52d);
const jackRing = createRing(0.62, 0.76, 0xd9564d);
scene.add(releaseRing, jackRing);
function createVoxelObject(radius, kind) {
const group = new THREE.Group();
const segments = kind === "jack" ? 3 : 5;
const cell = (radius * 2) / segments;
const cubeSize = cell * 0.91;
const cells = [];
const limit = segments / 2;
const maxDistance =
kind === "jack"
? Math.sqrt(2.45)
: Math.sqrt(6.05);
for (let x = -limit; x <= limit; x++) {
for (let y = -limit; y <= limit; y++) {
for (let z = -limit; z <= limit; z++) {
if (Math.hypot(x, y, z) <= maxDistance) {
cells.push({ x, y, z });
}
}
}
}
const material =
kind === "ghost"
? new THREE.MeshBasicMaterial({
color: 0x218576,
transparent: true,
opacity: 0.2,
depthWrite: false
})
: new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.68,
metalness: 0.035
});
const mesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(cubeSize, cubeSize, cubeSize),
material,
cells.length
);
const dummy = new THREE.Object3D();
const color = new THREE.Color();
cells.forEach((cellPosition, index) => {
dummy.position.set(
cellPosition.x * cell,
cellPosition.y * cell,
cellPosition.z * cell
);
dummy.updateMatrix();
mesh.setMatrixAt(index, dummy.matrix);
if (kind === "ball") {
color.set(0xf3b83f);
color.offsetHSL(
(cellPosition.x + cellPosition.z) * 0.006,
0,
((cellPosition.x * 7 + cellPosition.y * 3 + cellPosition.z) % 5) *
0.012
);
} else if (kind === "jack") {
if (cellPosition.y === 0) {
color.set(0xd94c45);
} else {
color.set(0xf4f0df);
}
} else {
color.set(0x218576);
}
mesh.setColorAt(index, color);
});
mesh.instanceMatrix.needsUpdate = true;
if (mesh.instanceColor) {
mesh.instanceColor.needsUpdate = true;
}
mesh.castShadow = kind !== "ghost";
mesh.receiveShadow = kind !== "ghost";
group.add(mesh);
group.userData.material = material;
return group;
}
const ball = createVoxelObject(BALL_RADIUS, "ball");
const jack = createVoxelObject(JACK_RADIUS, "jack");
const ghostBall = createVoxelObject(BALL_RADIUS, "ghost");
scene.add(ball, jack, ghostBall);
const cameraState = {
radius: 21,
theta: 0.12,
phi: 0.53,
target: new THREE.Vector3(0, 1, 0)
};
function updateCamera() {
const { radius, theta, phi, target } = cameraState;
camera.position.set(
target.x + radius * Math.sin(theta) * Math.cos(phi),
target.y + radius * Math.sin(phi),
target.z + radius * Math.cos(theta) * Math.cos(phi)
);
camera.lookAt(target);
}
function fitCamera() {
const distance = Number($("distance").value);
const verticalFov = THREE.MathUtils.degToRad(camera.fov);
const horizontalFov =
2 * Math.atan(Math.tan(verticalFov / 2) * camera.aspect);
const requiredRadius =
((distance / 2 + 2.2) / Math.tan(horizontalFov / 2)) * 1.08;
cameraState.radius = THREE.MathUtils.clamp(
Math.max(distance + 7, requiredRadius),
12,
78
);
}
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
cameraState.theta -= deltaX * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + deltaY * 0.005,
0.22,
1.12
);
previousPointerX = event.clientX;
previousPointerY = event.clientY;
});
function endDrag(event) {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
10,
82
);
},
{ passive: false }
);
const parameters = {
speed: 4.8,
deceleration: 1.2,
distance: 12,
startX: -6,
targetX: 6
};
const simulation = {
running: false,
elapsed: 0,
endTime: 4,
prediction: null,
actual: null
};
function readParameters() {
parameters.speed = Number($("speed").value);
parameters.deceleration = Number($("deceleration").value);
parameters.distance = Number($("distance").value);
parameters.startX = -parameters.distance / 2;
parameters.targetX = parameters.distance / 2;
}
function calculatePrediction() {
const stoppingDistance =
(parameters.speed * parameters.speed) /
(2 * parameters.deceleration);
const travelToContact =
parameters.distance - CONTACT_DISTANCE;
const hit = stoppingDistance >= travelToContact;
const finalCenterSeparation = hit
? CONTACT_DISTANCE
: parameters.distance - stoppingDistance;
const finalEdgeGap = hit
? 0
: Math.max(0, finalCenterSeparation - CONTACT_DISTANCE);
const predictedStopX = hit
? parameters.targetX - CONTACT_DISTANCE
: parameters.startX + stoppingDistance;
return {
stoppingDistance,
travelToContact,
hit,
finalCenterSeparation,
finalEdgeGap,
predictedStopX
};
}
function updateSliderFill(input) {
const min = Number(input.min);
const max = Number(input.max);
const value = Number(input.value);
const percentage = ((value - min) / (max - min)) * 100;
input.style.setProperty("--fill", `${percentage}%`);
}
function updateInterface() {
const prediction = calculatePrediction();
$("speedValue").textContent =
`${parameters.speed.toFixed(1)} m/s`;
$("decelerationValue").textContent =
`${parameters.deceleration.toFixed(2)} m/s²`;
$("distanceValue").textContent =
`${parameters.distance.toFixed(1)} m`;
$("stopMetric").textContent =
`${prediction.stoppingDistance.toFixed(2)} m`;
$("projectedMetric").textContent =
`${prediction.finalEdgeGap.toFixed(2)} m`;
if (simulation.actual) {
$("actualMetric").textContent =
`${simulation.actual.finalEdgeGap.toFixed(2)} m`;
$("actualDetail").textContent =
simulation.actual.hit ? "contact with jack" : "stopped before jack";
$("errorMetric").textContent =
`${(
simulation.actual.finalEdgeGap - prediction.finalEdgeGap
).toFixed(2)} m`;
} else {
$("actualMetric").textContent = "—";
$("actualDetail").textContent = "not released yet";
$("errorMetric").textContent = "—";
}
const centerSeparation = simulation.actual
? simulation.actual.finalCenterSeparation
: prediction.finalCenterSeparation;
$("centerMetric").textContent =
`${centerSeparation.toFixed(2)} m`;
const status = $("status");
status.classList.toggle("hit", simulation.actual?.hit === true);
if (simulation.running) {
status.textContent = "Rolling — deceleration is active.";
} else if (simulation.actual) {
status.textContent = simulation.actual.hit
? "Contact. Final edge separation: 0.00 m."
: `Stopped ${simulation.actual.finalEdgeGap.toFixed(
2
)} m before the jack.`;
} else {
status.textContent = prediction.hit
? `Projected contact with the jack.`
: `Ready to release — projected edge gap ${prediction.finalEdgeGap.toFixed(
2
)} m.`;
}
return prediction;
}
function layoutScene() {
readParameters();
ball.position.set(parameters.startX, BALL_RADIUS, 0);
ball.rotation.set(0, 0, 0);
jack.position.set(parameters.targetX, JACK_RADIUS, 0);
releaseRing.position.x = parameters.startX;
jackRing.position.x = parameters.targetX;
releaseLabel.position.x = parameters.startX;
jackLabel.position.x = parameters.targetX;
const prediction = calculatePrediction();
ghostBall.position.set(
prediction.predictedStopX,
BALL_RADIUS,
0
);
ghostBall.visible = true;
ghostBall.userData.material.color.set(
prediction.hit ? 0xd94c45 : 0x218576
);
simulation.running = false;
simulation.elapsed = 0;
simulation.actual = null;
$("release").disabled = false;
$("release").textContent = "Release ball";
updateInterface();
}
function addHistoryRow(prediction) {
const body = $("historyBody");
const row = document.createElement("tr");
const resultClass = prediction.hit
? "result-hit"
: "result-miss";
row.innerHTML = `
<td>${parameters.speed.toFixed(1)} m/s</td>
<td>${parameters.deceleration.toFixed(2)} m/s²</td>
<td>${prediction.stoppingDistance.toFixed(2)} m</td>
<td>${prediction.finalEdgeGap.toFixed(2)} m</td>
<td class="${resultClass}">${prediction.hit ? "HIT" : "MISS"}</td>
`;
body.prepend(row);
while (body.children.length > 6) {
body.lastElementChild.remove();
}
$("historyCount").textContent =
`${body.children.length} completed ${
body.children.length === 1 ? "run" : "runs"
}`;
$("emptyHistory").hidden = true;
$("tableWrap").hidden = false;
}
function releaseBall() {
if (simulation.running) return;
const prediction = calculatePrediction();
simulation.prediction = prediction;
simulation.running = true;
simulation.elapsed = 0;
simulation.endTime = parameters.speed / parameters.deceleration;
simulation.actual = null;
ball.position.set(parameters.startX, BALL_RADIUS, 0);
ball.rotation.set(0, 0, 0);
ghostBall.visible = true;
ghostBall.position.set(
prediction.predictedStopX,
BALL_RADIUS,
0
);
ghostBall.userData.material.color.set(
prediction.hit ? 0xd94c45 : 0x218576
);
$("release").disabled = true;
$("release").textContent = "Rolling…";
updateInterface();
}
function finishRun(prediction) {
simulation.running = false;
simulation.actual = {
hit: prediction.hit,
finalEdgeGap: prediction.finalEdgeGap,
finalCenterSeparation: prediction.finalCenterSeparation
};
ball.position.set(
prediction.hit
? parameters.targetX - CONTACT_DISTANCE
: parameters.startX + prediction.stoppingDistance,
BALL_RADIUS,
0
);
ghostBall.visible = false;
$("release").disabled = false;
$("release").textContent = "Roll again";
updateInterface();
addHistoryRow(prediction);
}
function updateSimulation(deltaTime) {
simulation.elapsed += deltaTime;
const elapsed = simulation.elapsed;
const speed = Math.max(
0,
parameters.speed - parameters.deceleration * elapsed
);
let traveled =
parameters.speed * elapsed -
0.5 * parameters.deceleration * elapsed * elapsed;
const prediction = simulation.prediction;
const contactX =
parameters.targetX - CONTACT_DISTANCE;
if (traveled >= prediction.travelToContact) {
traveled = prediction.travelToContact;
ball.position.x = contactX;
ball.rotation.z = -traveled / BALL_RADIUS;
finishRun(prediction);
return;
}
if (elapsed >= simulation.endTime) {
traveled = prediction.stoppingDistance;
ball.position.x =
parameters.startX + prediction.stoppingDistance;
ball.rotation.z = -traveled / BALL_RADIUS;
finishRun(prediction);
return;
}
ball.position.x = parameters.startX + traveled;
// Rolling without slipping: angular travel = distance / radius.
ball.rotation.z = -traveled / BALL_RADIUS;
$("actualMetric").textContent = `${(
Math.max(
0,
parameters.distance -
traveled -
CONTACT_DISTANCE
)
).toFixed(2)} m`;
$("actualDetail").textContent = "in progress";
}
for (const id of ["speed", "deceleration", "distance"]) {
const input = $(id);
updateSliderFill(input);
input.addEventListener("input", () => {
updateSliderFill(input);
layoutScene();
});
}
$("release").addEventListener("click", releaseBall);
$("reset").addEventListener("click", () => {
layoutScene();
});
window.addEventListener("keydown", (event) => {
const tagName = event.target.tagName;
if (["INPUT", "BUTTON", "SELECT", "TEXTAREA"].includes(tagName)) {
return;
}
if (event.code === "Space") {
event.preventDefault();
releaseBall();
}
if (event.key.toLowerCase() === "r") {
layoutScene();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
fitCamera();
});
layoutScene();
fitCamera();
updateCamera();
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const deltaTime = Math.min(clock.getDelta(), 0.05);
if (simulation.running) {
if (!simulation.prediction) {
simulation.prediction = calculatePrediction();
}
updateSimulation(deltaTime);
}
updateCamera();
renderer.render(scene, camera);
});
</script>
</body>
</html>
```