Prompt specification
Build or customize the Three.js 3D scene "Tune a Bounce to Reach a Shelf" 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: Tune a Bounce to Reach a Shelf
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/tune-a-bounce-to-reach-a-shelf-x3604
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Create a bounded trick-shot puzzle using one floor bounce and a target shelf. Validate the trajectory and energy loss under a declared simple collision model.
Working Three.js Starter (tune-a-bounce-to-reach-a-shelf-x3604):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>One Bounce — Trick-Shot Puzzle</title>
<style>
:root {
--bg: #071119;
--panel: rgba(10, 23, 32, 0.9);
--panel-border: rgba(140, 213, 225, 0.2);
--text: #edf8fa;
--muted: #91abb4;
--cyan: #58d9e8;
--amber: #ffbd69;
--green: #69e6a4;
--red: #ff7385;
}
* {
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;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
pointer-events: auto;
border: 1px solid var(--panel-border);
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.brand {
position: absolute;
top: 22px;
left: 24px;
max-width: 390px;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.75);
}
.eyebrow {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 5px 0 3px;
font-size: clamp(28px, 4vw, 48px);
line-height: 1;
letter-spacing: -0.045em;
}
.brand p {
margin: 9px 0 0;
color: #c2d4da;
font-size: 13px;
line-height: 1.5;
}
.controls {
position: absolute;
top: 20px;
right: 20px;
width: min(330px, calc(100vw - 40px));
max-height: calc(100vh - 40px);
overflow: auto;
padding: 17px;
border-radius: 16px;
scrollbar-width: thin;
scrollbar-color: #34505c transparent;
}
.panel-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.panel-title h2 {
margin: 0;
font-size: 14px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.counter {
color: var(--muted);
font-size: 11px;
white-space: nowrap;
}
.counter strong {
color: var(--text);
}
.status {
display: flex;
align-items: center;
gap: 8px;
min-height: 35px;
margin-bottom: 15px;
padding: 8px 10px;
border: 1px solid rgba(255, 255, 255, 0.09);
border-radius: 9px;
background: rgba(255, 255, 255, 0.035);
color: var(--muted);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.status::before {
width: 8px;
height: 8px;
flex: 0 0 auto;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 14px currentColor;
content: "";
}
.status.success {
border-color: rgba(105, 230, 164, 0.24);
background: rgba(105, 230, 164, 0.08);
color: var(--green);
}
.status.warn {
border-color: rgba(255, 189, 105, 0.24);
background: rgba(255, 189, 105, 0.08);
color: var(--amber);
}
.status.fail {
border-color: rgba(255, 115, 133, 0.24);
background: rgba(255, 115, 133, 0.08);
color: var(--red);
}
.control {
margin: 13px 0;
}
.control-head {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 7px;
font-size: 12px;
}
.control-head label {
color: #d8e6ea;
font-weight: 700;
}
output {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 5px 0;
border-radius: 999px;
outline: none;
background: #29404a;
accent-color: var(--cyan);
cursor: pointer;
}
.range-note {
margin-top: 3px;
color: #718b95;
font-size: 10px;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 15px;
}
button {
min-height: 39px;
border: 1px solid rgba(255, 255, 255, 0.11);
border-radius: 9px;
background: #17303a;
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease;
}
button:hover {
transform: translateY(-1px);
border-color: rgba(88, 217, 232, 0.55);
background: #1b3a46;
}
button:active {
transform: translateY(0);
}
button.primary {
grid-column: 1 / -1;
border-color: transparent;
background: var(--cyan);
color: #07161c;
font-size: 13px;
letter-spacing: 0.04em;
}
button.primary:hover {
background: #7ce8f2;
}
button:disabled {
opacity: 0.5;
cursor: wait;
transform: none;
}
.section {
margin-top: 16px;
padding-top: 14px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
}
.section-title {
margin-bottom: 9px;
color: #b7cbd1;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.validation-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
min-height: 27px;
color: var(--muted);
font-size: 11px;
}
.validation-row strong {
color: #d7e5e9;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
}
.validation-row strong.pass {
color: var(--green);
}
.validation-row strong.fail {
color: var(--red);
}
.model {
position: absolute;
bottom: 20px;
left: 20px;
width: min(355px, calc(100vw - 40px));
padding: 15px 17px;
border-radius: 14px;
}
.model h3 {
margin: 0 0 9px;
font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.model p {
margin: 6px 0;
color: #a9bec5;
font-size: 11px;
line-height: 1.55;
}
.equation {
color: #d6e7eb;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
}
.energy-readout {
margin-top: 9px;
padding: 9px 10px;
border-radius: 8px;
background: rgba(88, 217, 232, 0.06);
color: #bdd3d9;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
line-height: 1.6;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 10px;
color: #9db3bb;
font-size: 10px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend i {
width: 14px;
height: 2px;
display: inline-block;
background: var(--cyan);
}
.legend i.amber {
background: var(--amber);
}
.legend i.green {
background: var(--green);
}
.camera-hint {
position: absolute;
right: 22px;
bottom: 17px;
color: rgba(213, 234, 239, 0.72);
font-size: 10px;
text-align: right;
text-shadow: 0 2px 8px #000;
}
@media (max-width: 760px) {
.brand {
top: 15px;
left: 16px;
}
.brand p {
display: none;
}
.controls {
top: auto;
right: 10px;
bottom: 10px;
left: 10px;
width: auto;
max-height: 58vh;
padding: 14px;
}
.model,
.camera-hint {
display: none;
}
}
</style>
</head>
<body>
<div class="hud">
<header class="brand">
<div class="eyebrow">Trick-Shot Laboratory</div>
<h1>ONE BOUNCE</h1>
<p>
Reach the glowing target shelf using exactly one floor bounce.
The dashed trajectory is validated against the collision model.
</p>
</header>
<section class="controls panel" aria-label="Shot controls">
<div class="panel-title">
<h2>Shot setup</h2>
<div class="counter">
Attempts <strong id="attemptCount">0</strong> ·
Solved <strong id="successCount">0</strong>
</div>
</div>
<div id="status" class="status">Calculating trajectory</div>
<div class="control">
<div class="control-head">
<label for="speed">Launch speed</label>
<output id="speedValue" for="speed"></output>
</div>
<input id="speed" type="range" min="4" max="14" step="0.01" />
</div>
<div class="control">
<div class="control-head">
<label for="pitch">Elevation</label>
<output id="pitchValue" for="pitch"></output>
</div>
<input id="pitch" type="range" min="20" max="75" step="0.1" />
<div class="range-note">Positive elevation launches above the floor.</div>
</div>
<div class="control">
<div class="control-head">
<label for="yaw">Heading</label>
<output id="yawValue" for="yaw"></output>
</div>
<input id="yaw" type="range" min="-180" max="180" step="0.1" />
<div class="range-note">0° points toward the back wall; positive turns right.</div>
</div>
<div class="buttons">
<button id="launchButton" class="primary" type="button">Launch shot</button>
<button id="resetButton" type="button">Reset ball</button>
<button id="solutionButton" type="button">Load solution</button>
</div>
<div class="section">
<div class="section-title">Trajectory validation</div>
<div class="validation-row">
<span>Floor bounces</span>
<strong id="bounceValue">—</strong>
</div>
<div class="validation-row">
<span>Target shelf intercept</span>
<strong id="shelfValue">—</strong>
</div>
<div class="validation-row">
<span>Target error</span>
<strong id="errorValue">—</strong>
</div>
<div class="validation-row">
<span>Floor-collision K retained</span>
<strong id="energyValue">—</strong>
</div>
<div class="validation-row">
<span>Boundary check</span>
<strong id="boundsValue">—</strong>
</div>
</div>
</section>
<aside class="model panel">
<h3>Declared simple collision model</h3>
<p>
Fixed-step rigid sphere, radius <strong>0.22 m</strong>, mass
<strong>0.18 kg</strong>, gravity <strong>9.81 m/s²</strong>,
integration step <strong>1/120 s</strong>.
</p>
<p class="equation">
Floor: v′y = −0.76 vy; v′x = vx; v′z = vz<br />
Wall: v′n = −0.55 vn; tangential velocity is unchanged<br />
Shelf: perfectly inelastic capture; remaining kinetic energy is removed
</p>
<p>
No tangential friction. A successful shot requires one floor bounce
before landing inside the 0.46 m target radius.
</p>
<div id="energyReadout" class="energy-readout">
Waiting for trajectory…
</div>
<div class="legend">
<span><i></i>Before bounce</span>
<span><i class="amber"></i>After bounce</span>
<span><i class="green"></i>Validated solution</span>
</div>
</aside>
<div class="camera-hint">
Drag: orbit · Shift/right-drag: pan · Wheel: zoom<br />
Space: launch · Arrow keys: adjust aim
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Declared model and puzzle geometry
// -------------------------------------------------------------------------
const MODEL = Object.freeze({
gravity: 9.81,
mass: 0.18,
radius: 0.22,
floorRestitution: 0.76,
wallRestitution: 0.55,
timeStep: 1 / 120,
halfWidth: 8,
halfDepth: 6,
ceiling: 5.2,
shelfTop: 0.68,
shelfWidth: 2.8,
shelfDepth: 1.5,
shelfX: 3,
shelfZ: -5.25,
targetX: 3,
targetZ: -4.9,
targetRadius: 0.46
});
const START = new THREE.Vector3(-5.8, 0.28, 2.8);
const solution = {
speed: 8.55,
pitch: 55,
yaw:
(Math.atan2(
MODEL.targetX - START.x,
-(MODEL.targetZ - START.z)
) *
180) /
Math.PI
};
const ui = {
speed: document.querySelector("#speed"),
pitch: document.querySelector("#pitch"),
yaw: document.querySelector("#yaw"),
speedValue: document.querySelector("#speedValue"),
pitchValue: document.querySelector("#pitchValue"),
yawValue: document.querySelector("#yawValue"),
launch: document.querySelector("#launchButton"),
reset: document.querySelector("#resetButton"),
solution: document.querySelector("#solutionButton"),
status: document.querySelector("#status"),
attemptCount: document.querySelector("#attemptCount"),
successCount: document.querySelector("#successCount"),
bounceValue: document.querySelector("#bounceValue"),
shelfValue: document.querySelector("#shelfValue"),
errorValue: document.querySelector("#errorValue"),
energyValue: document.querySelector("#energyValue"),
boundsValue: document.querySelector("#boundsValue"),
energyReadout: document.querySelector("#energyReadout")
};
// -------------------------------------------------------------------------
// Renderer, scene, camera
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x071119);
scene.fog = new THREE.Fog(0x071119, 19, 38);
const camera = new THREE.PerspectiveCamera(
46,
innerWidth / innerHeight,
0.1,
80
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
document.body.prepend(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(
0xbfeeff,
0x162028,
1.65
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff1d6, 2.6);
keyLight.position.set(-7, 13, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0006;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x44c8ff, 1.3);
rimLight.position.set(8, 7, -9);
scene.add(rimLight);
const targetLight = new THREE.PointLight(0x45ffd1, 3.2, 7, 2);
targetLight.position.set(MODEL.targetX, 1.8, MODEL.targetZ);
scene.add(targetLight);
// Direct camera controls: no examples/addons are imported.
const cameraTarget = new THREE.Vector3(0, 0.7, 0);
const cameraState = {
theta: 0.64,
phi: 1.02,
radius: 19.5
};
function updateCamera() {
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraTarget.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraTarget.y + cameraState.radius * Math.cos(cameraState.phi),
cameraTarget.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
let pointerState = null;
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerState = {
id: event.pointerId,
x: event.clientX,
y: event.clientY,
pan: event.button === 2 || event.shiftKey
};
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerState || pointerState.id !== event.pointerId) return;
const dx = event.clientX - pointerState.x;
const dy = event.clientY - pointerState.y;
pointerState.x = event.clientX;
pointerState.y = event.clientY;
if (pointerState.pan) {
const right = new THREE.Vector3(
Math.cos(cameraState.theta),
0,
-Math.sin(cameraState.theta)
);
const forward = new THREE.Vector3(
-Math.sin(cameraState.theta),
0,
-Math.cos(cameraState.theta)
);
const scale = cameraState.radius * 0.0012;
cameraTarget.addScaledVector(right, -dx * scale);
cameraTarget.addScaledVector(forward, -dy * scale);
cameraTarget.x = THREE.MathUtils.clamp(
cameraTarget.x,
-8,
8
);
cameraTarget.z = THREE.MathUtils.clamp(
cameraTarget.z,
-8,
8
);
} else {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.005,
0.35,
1.38
);
}
updateCamera();
});
function releasePointer(event) {
if (pointerState?.id === event.pointerId) pointerState = null;
}
renderer.domElement.addEventListener("pointerup", releasePointer);
renderer.domElement.addEventListener("pointercancel", releasePointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
10,
29
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraState.theta = 0.64;
cameraState.phi = 1.02;
cameraState.radius = 19.5;
cameraTarget.set(0, 0.7, 0);
updateCamera();
});
// -------------------------------------------------------------------------
// Low-poly arena construction
// -------------------------------------------------------------------------
function standardMaterial(color, extra = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0.05,
flatShading: true,
...extra
});
}
function addBox(
width,
height,
depth,
x,
y,
z,
color,
extra = {},
parent = scene
) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
standardMaterial(color, extra)
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
addBox(
16.4,
0.36,
12.4,
0,
-0.18,
0,
0x172a35
);
const grid = new THREE.GridHelper(16, 16, 0x49727c, 0x29444e);
grid.position.y = 0.006;
grid.scale.z = 0.75;
grid.material.transparent = true;
grid.material.opacity = 0.38;
scene.add(grid);
// Back and side walls.
addBox(16.4, 3.8, 0.28, 0, 1.9, -6.14, 0x203844);
addBox(0.28, 3.8, 12.3, -8.14, 1.9, 0, 0x1d333e);
addBox(0.28, 3.8, 12.3, 8.14, 1.9, 0, 0x1d333e);
// Front boundary: solid lower rail plus a subtle transparent upper wall.
addBox(16.4, 0.72, 0.25, 0, 0.36, 6.14, 0x203844);
const frontUpper = new THREE.Mesh(
new THREE.BoxGeometry(16.4, 4.35, 0.12),
standardMaterial(0x6ea8b5, {
transparent: true,
opacity: 0.08,
depthWrite: false
})
);
frontUpper.position.set(0, 3.02, 6.14);
scene.add(frontUpper);
// Corner posts and top frame make the full collision volume legible.
for (const x of [-8, 8]) {
for (const z of [-6, 6]) {
addBox(0.25, 5.2, 0.25, x, 2.6, z, 0x36515c);
}
}
addBox(16.2, 0.18, 0.18, 0, 5.2, -6, 0x36515c);
addBox(16.2, 0.18, 0.18, 0, 5.2, 6, 0x36515c);
addBox(0.18, 0.18, 12.1, -8, 5.2, 0, 0x36515c);
addBox(0.18, 0.18, 12.1, 8, 5.2, 0, 0x36515c);
// Decorative wall panels.
for (let i = 0; i < 8; i++) {
const panel = addBox(
1.25,
0.55,
0.06,
-6.3 + i * 1.8,
2.65,
-5.96,
i % 2 ? 0x294753 : 0x243d48
);
panel.rotation.z = (i % 2 ? 1 : -1) * 0.07;
}
// Target shelf and supports.
addBox(
MODEL.shelfWidth,
0.18,
MODEL.shelfDepth,
MODEL.shelfX,
MODEL.shelfTop - 0.09,
MODEL.shelfZ,
0x46626d
);
addBox(
0.18,
MODEL.shelfTop - 0.18,
0.18,
MODEL.shelfX - 1.05,
(MODEL.shelfTop - 0.18) / 2,
-5.72,
0x2d4955
);
addBox(
0.18,
MODEL.shelfTop - 0.18,
0.18,
MODEL.shelfX + 1.05,
(MODEL.shelfTop - 0.18) / 2,
-5.72,
0x2d4955
);
const targetPad = new THREE.Mesh(
new THREE.CylinderGeometry(
MODEL.targetRadius,
MODEL.targetRadius,
0.025,
12
),
standardMaterial(0x123d38, {
emissive: 0x0a332a,
emissiveIntensity: 0.75
})
);
targetPad.position.set(
MODEL.targetX,
MODEL.shelfTop + 0.0125,
MODEL.targetZ
);
targetPad.receiveShadow = true;
scene.add(targetPad);
const targetRing = new THREE.Mesh(
new THREE.TorusGeometry(MODEL.targetRadius, 0.045, 5, 18),
standardMaterial(0x62ffd5, {
emissive: 0x2dffbf,
emissiveIntensity: 2.2,
metalness: 0.2,
roughness: 0.28
})
);
targetRing.rotation.x = Math.PI / 2;
targetRing.position.set(
MODEL.targetX,
MODEL.shelfTop + 0.065,
MODEL.targetZ
);
scene.add(targetRing);
const beaconMaterial = new THREE.MeshBasicMaterial({
color: 0x52ffd0,
transparent: true,
opacity: 0.11,
depthWrite: false
});
const targetBeacon = new THREE.Mesh(
new THREE.CylinderGeometry(0.3, 0.52, 2.6, 8, 1, true),
beaconMaterial
);
targetBeacon.position.set(
MODEL.targetX,
MODEL.shelfTop + 1.3,
MODEL.targetZ
);
scene.add(targetBeacon);
// Launch pad.
const launchPad = new THREE.Mesh(
new THREE.TorusGeometry(0.58, 0.035, 5, 20),
standardMaterial(0x58d9e8, {
emissive: 0x176879,
emissiveIntensity: 1.1
})
);
launchPad.rotation.x = Math.PI / 2;
launchPad.position.set(START.x, 0.035, START.z);
scene.add(launchPad);
const launchArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(START.x, 0.12, START.z),
2.35,
0x58d9e8,
0.32,
0.17
);
scene.add(launchArrow);
// Ball.
const ball = new THREE.Group();
const ballMesh = new THREE.Mesh(
new THREE.IcosahedronGeometry(MODEL.radius, 1),
standardMaterial(0xff9b4a, {
roughness: 0.55,
metalness: 0.08,
emissive: 0x4a1600,
emissiveIntensity: 0.25
})
);
ballMesh.castShadow = true;
ballMesh.receiveShadow = true;
ball.add(ballMesh);
ball.position.copy(START);
scene.add(ball);
// Canvas-generated labels use no external assets.
function makeLabel(text, color = "#8ff4ff") {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.fillStyle = "rgba(7, 19, 27, 0.82)";
context.beginPath();
context.roundRect(8, 8, 496, 112, 18);
context.fill();
context.strokeStyle = color;
context.lineWidth = 5;
context.stroke();
context.fillStyle = color;
context.font = "800 48px system-ui";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 65);
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.2, 0.55, 1);
return sprite;
}
const targetLabel = makeLabel("TARGET", "#72ffda");
targetLabel.position.set(MODEL.targetX, 1.85, -5.85);
scene.add(targetLabel);
const startLabel = makeLabel("ONE BOUNCE", "#75dff0");
startLabel.position.set(START.x, 1.1, START.z);
startLabel.scale.set(1.8, 0.45, 1);
scene.add(startLabel);
// -------------------------------------------------------------------------
// Deterministic trajectory simulation and validation
// -------------------------------------------------------------------------
function kineticEnergy(velocity) {
return 0.5 * MODEL.mass * velocity.lengthSq();
}
function onShelf(x, z) {
return (
Math.abs(x - MODEL.shelfX) <= MODEL.shelfWidth / 2 &&
Math.abs(z - MODEL.shelfZ) <= MODEL.shelfDepth / 2
);
}
function simulateShot(parameters, maxSeconds = 9) {
const pitch = THREE.MathUtils.degToRad(parameters.pitch);
const yaw = THREE.MathUtils.degToRad(parameters.yaw);
const horizontalSpeed =
Math.cos(pitch) * parameters.speed;
const verticalSpeed =
Math.sin(pitch) * parameters.speed;
const position = START.clone();
const velocity = new THREE.Vector3(
Math.sin(yaw) * horizontalSpeed,
verticalSpeed,
-Math.cos(yaw) * horizontalSpeed
);
const points = [position.clone()];
const events = [];
let floorBounces = 0;
let wallContacts = 0;
let shelfHit = false;
let targetError = Infinity;
let success = false;
let inBounds = true;
let reason = "The trajectory did not reach the target shelf.";
const maxX = MODEL.halfWidth - MODEL.radius;
const maxZ = MODEL.halfDepth - MODEL.radius;
const maxY = MODEL.ceiling - MODEL.radius;
const shelfCollisionY = MODEL.shelfTop + MODEL.radius;
const dt = MODEL.timeStep;
const maxSteps = Math.ceil(maxSeconds / dt);
for (let step = 0; step < maxSteps; step++) {
const previous = position.clone();
// Semi-implicit Euler integration.
velocity.y -= MODEL.gravity * dt;
position.addScaledVector(velocity, dt);
// Floor collision.
if (position.y < MODEL.radius && velocity.y < 0) {
position.y = MODEL.radius;
const preEnergy = kineticEnergy(velocity);
velocity.y = -velocity.y * MODEL.floorRestitution;
const postEnergy = kineticEnergy(velocity);
floorBounces++;
events.push({
type: "floor",
step: step + 1,
position: position.clone(),
preEnergy,
postEnergy,
retained: postEnergy / preEnergy
});
if (floorBounces > 1) {
reason =
"A second floor bounce violates the one-bounce rule.";
}
}
// Side walls: reflect only the normal velocity component.
if (position.x > maxX && velocity.x > 0) {
position.x = maxX;
const preEnergy = kineticEnergy(velocity);
velocity.x = -velocity.x * MODEL.wallRestitution;
const postEnergy = kineticEnergy(velocity);
wallContacts++;
events.push({
type: "wall",
step: step + 1,
position: position.clone(),
preEnergy,
postEnergy,
retained: postEnergy / preEnergy
});
} else if (position.x < -maxX && velocity.x < 0) {
position.x = -maxX;
const preEnergy = kineticEnergy(velocity);
velocity.x = -velocity.x * MODEL.wallRestitution;
const postEnergy = kineticEnergy(velocity);
wallContacts++;
events.push({
type: "wall",
step: step + 1,
position: position.clone(),
preEnergy,
postEnergy,
retained: postEnergy / preEnergy
});
}
// Back and front walls.
if (position.z < -maxZ && velocity.z < 0) {
position.z = -maxZ;
const preEnergy = kineticEnergy(velocity);
velocity.z = -velocity.z * MODEL.wallRestitution;
const postEnergy = kineticEnergy(velocity);
wallContacts++;
events.push({
type: "wall",
step: step + 1,
position: position.clone(),
preEnergy,
postEnergy,
retained: postEnergy / preEnergy
});
} else if (position.z > maxZ && velocity.z > 0) {
position.z = maxZ;
const preEnergy = kineticEnergy(velocity);
velocity.z = -velocity.z * MODEL.wallRestitution;
const postEnergy = kineticEnergy(velocity);
wallContacts++;
events.push({
type: "wall",
step: step + 1,
position: position.clone(),
preEnergy,
postEnergy,
retained: postEnergy / preEnergy
});
}
// Ceiling.
if (position.y > maxY && velocity.y > 0) {
position.y = maxY;
const preEnergy = kineticEnergy(velocity);
velocity.y = -velocity.y * MODEL.floorRestitution;
const postEnergy = kineticEnergy(velocity);
events.push({
type: "ceiling",
step: step + 1,
position: position.clone(),
preEnergy,
postEnergy,
retained: postEnergy / preEnergy
});
}
// Swept crossing of the shelf's horizontal collision plane.
if (
velocity.y < 0 &&
previous.y >= shelfCollisionY &&
position.y <= shelfCollisionY &&
onShelf(position.x, position.z)
) {
const denominator = previous.y - position.y;
const fraction =
denominator > 0
? (previous.y - shelfCollisionY) / denominator
: 0;
const hit = previous.clone().lerp(position, fraction);
hit.y = shelfCollisionY;
position.copy(hit);
shelfHit = true;
targetError = Math.hypot(
position.x - MODEL.targetX,
position.z - MODEL.targetZ
);
const preEnergy = kineticEnergy(velocity);
velocity.set(0, 0, 0);
const postEnergy = 0;
events.push({
type: "shelf",
step: step + 1,
position: position.clone(),
preEnergy,
postEnergy,
retained: 0,
targetError
});
success =
floorBounces === 1 &&
targetError <= MODEL.targetRadius;
reason = success
? "Validated: one floor bounce followed by a target-shelf capture."
: floorBounces !== 1
? "The shelf was reached, but the one-bounce rule was not met."
: "The shelf caught the ball outside the target radius.";
points.push(position.clone());
break;
}
points.push(position.clone());
if (
position.x < -maxX - 0.01 ||
position.x > maxX + 0.01 ||
position.z < -maxZ - 0.01 ||
position.z > maxZ + 0.01 ||
position.y < MODEL.radius - 0.01 ||
position.y > maxY + 0.01
) {
inBounds = false;
}
if (floorBounces > 1) break;
}
const floorEvent = events.find((event) => event.type === "floor");
const shelfEvent = events.find((event) => event.type === "shelf");
return {
points,
events,
floorBounces,
wallContacts,
shelfHit,
targetError,
success,
inBounds,
reason,
floorEvent,
shelfEvent
};
}
// -------------------------------------------------------------------------
// Trajectory visualization
// -------------------------------------------------------------------------
const pathGroup = new THREE.Group();
scene.add(pathGroup);
function disposePathChildren() {
while (pathGroup.children.length) {
const child = pathGroup.children.pop();
child.traverse((object) => {
object.geometry?.dispose();
if (Array.isArray(object.material)) {
object.material.forEach((material) => material.dispose());
} else {
object.material?.dispose();
}
});
}
}
function addPathLine(points, color, dashed = false) {
if (points.length < 2) return;
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = dashed
? new THREE.LineDashedMaterial({
color,
dashSize: 0.19,
gapSize: 0.11,
transparent: true,
opacity: 0.88,
depthWrite: false
})
: new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.82,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
if (dashed) line.computeLineDistances();
pathGroup.add(line);
}
function renderTrajectory(simulation) {
disposePathChildren();
const floorEvent = simulation.floorEvent;
const cut = floorEvent ? floorEvent.step : simulation.points.length - 1;
addPathLine(
simulation.points.slice(0, cut + 1),
0x58d9e8,
false
);
addPathLine(
simulation.points.slice(cut),
simulation.success ? 0x69e6a4 : 0xffbd69,
true
);
if (floorEvent) {
const marker = new THREE.Group();
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.38, 0.025, 4, 24),
new THREE.MeshBasicMaterial({ color: 0xffbd69 })
);
ring.rotation.x = Math.PI / 2;
ring.position.set(
floorEvent.position.x,
0.027,
floorEvent.position.z
);
const pin = new THREE.Mesh(
new THREE.CylinderGeometry(0.018, 0.018, 0.42, 6),
new THREE.MeshBasicMaterial({ color: 0xffbd69 })
);
pin.position.set(
floorEvent.position.x,
0.21,
floorEvent.position.z
);
marker.add(ring, pin);
pathGroup.add(marker);
}
for (const event of simulation.events) {
if (event.type !== "wall") continue;
const marker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.1, 0),
new THREE.MeshBasicMaterial({ color: 0xff7385 })
);
marker.position.copy(event.position);
pathGroup.add(marker);
}
if (simulation.shelfHit) {
const marker = new THREE.Mesh(
new THREE.SphereGeometry(0.095, 8, 6),
new THREE.MeshBasicMaterial({
color: simulation.success ? 0x69e6a4 : 0xff7385
})
);
marker.position.copy(simulation.events.at(-1).position);
pathGroup.add(marker);
}
}
// -------------------------------------------------------------------------
// UI state and validation readout
// -------------------------------------------------------------------------
let currentParameters = { ...solution };
let currentSimulation = null;
let activeShot = null;
let attempts = 0;
let successes = 0;
function setStatus(text, type = "") {
ui.status.textContent = text;
ui.status.className = `status ${type}`.trim();
}
function setValidation(element, text, pass) {
element.textContent = text;
element.className = pass ? "pass" : "fail";
}
function updateControlLabels() {
ui.speedValue.textContent = `${Number(ui.speed.value).toFixed(2)} m/s`;
ui.pitchValue.textContent = `${Number(ui.pitch.value).toFixed(1)}°`;
ui.yawValue.textContent = `${Number(ui.yaw.value).toFixed(1)}°`;
}
function updateValidation(simulation) {
const floorEvent = simulation.floorEvent;
const shelfEvent = simulation.shelfEvent;
setValidation(
ui.bounceValue,
`${simulation.floorBounces} / 1`,
simulation.floorBounces === 1
);
setValidation(
ui.shelfValue,
simulation.shelfHit ? "INTERCEPTED" : "MISSED",
simulation.shelfHit
);
setValidation(
ui.errorValue,
Number.isFinite(simulation.targetError)
? `${simulation.targetError.toFixed(3)} m`
: "NO CONTACT",
Number.isFinite(simulation.targetError) &&
simulation.targetError <= MODEL.targetRadius
);
if (floorEvent) {
const retained = floorEvent.retained * 100;
setValidation(
ui.energyValue,
`${retained.toFixed(1)}%`,
retained > 0 && retained <= 100
);
} else {
setValidation(ui.energyValue, "NO FLOOR CONTACT", false);
}
setValidation(
ui.boundsValue,
simulation.inBounds ? "INSIDE" : "ESCAPED",
simulation.inBounds
);
if (floorEvent && shelfEvent) {
const floorLoss =
(floorEvent.preEnergy - floorEvent.postEnergy) *
100;
ui.energyReadout.innerHTML =
`Floor bounce: ${floorEvent.preEnergy.toFixed(2)} J → ` +
`${floorEvent.postEnergy.toFixed(2)} J<br>` +
`Collision loss: ${floorLoss.toFixed(1)}% · ` +
`${floorEvent.retained * 100 > 0 ? "restitution applied" : ""}<br>` +
`Shelf capture: ${shelfEvent.preEnergy.toFixed(2)} J → 0.00 J`;
} else if (floorEvent) {
const floorLoss =
(floorEvent.preEnergy - floorEvent.postEnergy) * 100;
ui.energyReadout.innerHTML =
`Floor bounce: ${floorEvent.preEnergy.toFixed(2)} J → ` +
`${floorEvent.postEnergy.toFixed(2)} J<br>` +
`Collision loss: ${floorLoss.toFixed(1)}%<br>` +
`Shelf capture: no contact`;
} else {
ui.energyReadout.textContent =
"No floor collision in the predicted trajectory.";
}
if (simulation.success) {
setStatus("Valid trick shot", "success");
} else if (simulation.floorBounces > 1) {
setStatus("One-bounce rule failed", "fail");
} else if (simulation.shelfHit) {
setStatus("Target radius missed", "warn");
} else {
setStatus("Trajectory misses shelf", "warn");
}
}
function readParameters() {
return {
speed: Number(ui.speed.value),
pitch: Number(ui.pitch.value),
yaw: Number(ui.yaw.value)
};
}
function updateAimArrow() {
const yaw = THREE.MathUtils.degToRad(currentParameters.yaw);
launchArrow.setDirection(
new THREE.Vector3(Math.sin(yaw), 0, -Math.cos(yaw))
);
}
function cancelFlight() {
activeShot = null;
ball.position.copy(START);
ball.rotation.set(0, 0, 0);
ui.launch.disabled = false;
ui.launch.textContent = "Launch shot";
}
function updatePreview() {
cancelFlight();
currentParameters = readParameters();
updateControlLabels();
updateAimArrow();
currentSimulation = simulateShot(currentParameters);
renderTrajectory(currentSimulation);
updateValidation(currentSimulation);
}
// -------------------------------------------------------------------------
// Low-poly impact particles
// -------------------------------------------------------------------------
const particles = [];
const particleGeometry = new THREE.TetrahedronGeometry(0.055, 0);
function spawnBurst(position, successful = false) {
const colors = successful
? [0x69e6a4, 0x58d9e8, 0xffd979]
: [0xffbd69, 0xff9b4a, 0xe7f8fa];
for (let i = 0; i < 16; i++) {
const material = new THREE.MeshBasicMaterial({
color: colors[i % colors.length],
transparent: true,
opacity: 1,
depthWrite: false
});
const mesh = new THREE.Mesh(particleGeometry, material);
mesh.position.copy(position);
mesh.position.y += successful ? 0.12 : 0;
scene.add(mesh);
const life = 0.55 + Math.random() * 0.25;
particles.push({
mesh,
life,
maxLife: life,
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 2.8,
0.8 + Math.random() * 2.4,
(Math.random() - 0.5) * 2.8
)
});
}
}
function updateParticles(delta) {
for (let i = particles.length - 1; i >= 0; i--) {
const particle = particles[i];
particle.life -= delta;
particle.velocity.y -= 6 * delta;
particle.mesh.position.addScaledVector(
particle.velocity,
delta
);
particle.mesh.rotation.x += delta * 7;
particle.mesh.rotation.y += delta * 9;
particle.mesh.material.opacity = Math.max(
0,
particle.life / particle.maxLife
);
if (particle.life <= 0) {
scene.remove(particle.mesh);
particle.mesh.material.dispose();
particles.splice(i, 1);
}
}
}
// -------------------------------------------------------------------------
// Shot playback
// -------------------------------------------------------------------------
function launchShot() {
if (activeShot) return;
cancelFlight();
currentParameters = readParameters();
currentSimulation = simulateShot(currentParameters);
renderTrajectory(currentSimulation);
updateValidation(currentSimulation);
attempts++;
ui.attemptCount.textContent = String(attempts);
activeShot = {
simulation: currentSimulation,
startedAt: performance.now(),
floorTriggered: false
};
ui.launch.disabled = true;
ui.launch.textContent = "Shot in flight";
setStatus("Ball in flight", "warn");
pathGroup.traverse((object) => {
if (object.material) {
object.material.opacity *= 0.45;
}
});
}
function finishShot() {
if (!activeShot) return;
const simulation = activeShot.simulation;
const finalPosition =
simulation.points.at(-1) ?? START;
ball.position.copy(finalPosition);
if (simulation.success) {
successes++;
ui.successCount.textContent = String(successes);
spawnBurst(finalPosition, true);
} else if (simulation.floorEvent) {
spawnBurst(simulation.floorEvent.position, false);
}
activeShot = null;
ui.launch.disabled = false;
ui.launch.textContent = "Launch shot";
updateValidation(simulation);
}
function animateBall(now) {
if (!activeShot) return;
const simulation = activeShot.simulation;
const elapsed = (now - activeShot.startedAt) / 1000;
const sample = elapsed / MODEL.timeStep;
const index = Math.floor(sample);
if (
simulation.floorEvent &&
!activeShot.floorTriggered &&
index >= simulation.floorEvent.step
) {
activeShot.floorTriggered = true;
spawnBurst(simulation.floorEvent.position, false);
}
if (index >= simulation.points.length - 1) {
finishShot();
return;
}
const a = simulation.points[index];
const b = simulation.points[Math.min(index + 1, simulation.points.length - 1)];
ball.position.copy(a).lerp(b, sample - index);
ball.rotation.x += 0.12;
ball.rotation.z += 0.08;
}
// -------------------------------------------------------------------------
// Input
// -------------------------------------------------------------------------
ui.speed.addEventListener("input", updatePreview);
ui.pitch.addEventListener("input", updatePreview);
ui.yaw.addEventListener("input", updatePreview);
ui.launch.addEventListener("click", launchShot);
ui.reset.addEventListener("click", () => {
updatePreview();
});
ui.solution.addEventListener("click", () => {
ui.speed.value = String(solution.speed);
ui.pitch.value = String(solution.pitch);
ui.yaw.value = String(solution.yaw);
updatePreview();
});
addEventListener("keydown", (event) => {
const tag = document.activeElement?.tagName;
if (tag === "INPUT" || tag === "BUTTON") return;
if (event.code === "Space") {
event.preventDefault();
launchShot();
return;
}
let changed = false;
if (event.code === "ArrowLeft") {
ui.yaw.value = String(
Number(ui.yaw.value) - (event.shiftKey ? 0.1 : 1)
);
changed = true;
}
if (event.code === "ArrowRight") {
ui.yaw.value = String(
Number(ui.yaw.value) + (event.shiftKey ? 0.1 : 1)
);
changed = true;
}
if (event.code === "ArrowUp") {
ui.pitch.value = String(
Math.min(75, Number(ui.pitch.value) + 0.5)
);
changed = true;
}
if (event.code === "ArrowDown") {
ui.pitch.value = String(
Math.max(20, Number(ui.pitch.value) - 0.5)
);
changed = true;
}
if (changed) {
event.preventDefault();
updatePreview();
}
});
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Start and render loop
// -------------------------------------------------------------------------
ui.speed.value = String(solution.speed);
ui.pitch.value = String(solution.pitch);
ui.yaw.value = String(solution.yaw);
updatePreview();
const clock = new THREE.Clock();
renderer.setAnimationLoop(() => {
const delta = Math.min(clock.getDelta(), 0.05);
const elapsed = clock.elapsedTime;
animateBall(performance.now());
updateParticles(delta);
const pulse = 1 + Math.sin(elapsed * 4.2) * 0.065;
targetRing.scale.setScalar(pulse);
targetRing.rotation.z = elapsed * 0.28;
beaconMaterial.opacity = 0.075 + Math.sin(elapsed * 3) * 0.025;
launchPad.rotation.z = elapsed * 0.18;
renderer.render(scene, camera);
});
</script>
</body>
</html>
```