Prompt specification
Build or customize the Three.js 3D scene "Ball track with height-energy markers" 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: Ball track with height-energy markers
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/ball-track-with-height-energy-markers-x1377
Scene Description Prompt:
A low-poly ball follows a valley track under an ideal energy model, beside a height ruler. Three.js from cdnjs, one HTML file.
Working Three.js Starter (ball-track-with-height-energy-markers-x1377):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Valley Energy Lab</title>
<style>
:root {
color-scheme: dark;
--cyan: #55e6d5;
--orange: #ffb454;
--muted: #8fa4b8;
--panel: rgba(12, 22, 35, 0.88);
--line: rgba(150, 190, 215, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #08111d;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#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: 24px;
left: 28px;
pointer-events: none;
user-select: none;
}
.brand .eyebrow {
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
.brand h1 {
margin: 7px 0 0;
color: #f4f8fb;
font-size: clamp(24px, 3vw, 42px);
font-weight: 650;
letter-spacing: -0.04em;
}
.brand p {
margin: 6px 0 0;
color: var(--muted);
font-size: 12px;
}
.panel {
position: fixed;
top: 22px;
right: 22px;
width: min(326px, calc(100vw - 28px));
padding: 18px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 16px;
}
.panel-header strong {
color: #eef6fa;
font-size: 13px;
letter-spacing: 0.04em;
text-transform: uppercase;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.status::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
content: "";
}
.status.paused {
color: var(--orange);
}
.formula {
padding: 12px 13px;
border: 1px solid rgba(85, 230, 213, 0.15);
border-radius: 12px;
background: rgba(85, 230, 213, 0.055);
color: #dce8ee;
text-align: center;
font-family: Georgia, "Times New Roman", serif;
font-size: 16px;
}
.formula small {
display: block;
margin-top: 5px;
color: var(--muted);
font-family: Inter, ui-sans-serif, system-ui, sans-serif;
font-size: 9px;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.metrics {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 14px;
}
.metric {
min-height: 65px;
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.025);
}
.metric span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric strong {
color: #f4f8fb;
font-size: 19px;
font-weight: 650;
letter-spacing: -0.03em;
}
.metric strong em {
margin-left: 3px;
color: var(--muted);
font-size: 10px;
font-style: normal;
font-weight: 600;
}
.energy {
margin-top: 15px;
padding-top: 14px;
border-top: 1px solid var(--line);
}
.energy-heading {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
color: var(--muted);
font-size: 9px;
font-weight: 750;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.energy-heading b {
color: #e8f0f4;
font-weight: 700;
}
.bar-row {
display: grid;
grid-template-columns: 25px 1fr 52px;
align-items: center;
gap: 8px;
margin: 8px 0;
color: var(--muted);
font-size: 9px;
font-weight: 700;
}
.bar {
height: 7px;
overflow: hidden;
border-radius: 99px;
background: rgba(255, 255, 255, 0.07);
}
.bar > div {
width: 0;
height: 100%;
border-radius: inherit;
transition: width 80ms linear;
}
#keBar {
background: var(--cyan);
box-shadow: 0 0 14px rgba(85, 230, 213, 0.45);
}
#peBar {
background: var(--orange);
box-shadow: 0 0 14px rgba(255, 180, 84, 0.4);
}
.bar-row output {
color: #dce6eb;
text-align: right;
}
.release {
margin-top: 16px;
padding-top: 14px;
border-top: 1px solid var(--line);
}
.release label {
display: flex;
justify-content: space-between;
margin-bottom: 9px;
color: #dfe8ed;
font-size: 10px;
font-weight: 700;
}
.release output {
color: var(--orange);
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 7px 0 3px;
border-radius: 99px;
outline: none;
appearance: none;
background: linear-gradient(
to right,
var(--orange) 0%,
var(--orange) 57%,
rgba(255, 255, 255, 0.1) 57%,
rgba(255, 255, 255, 0.1) 100%
);
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #172535;
border-radius: 50%;
appearance: none;
background: var(--orange);
box-shadow: 0 0 0 1px var(--orange);
cursor: pointer;
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #172535;
border-radius: 50%;
background: var(--orange);
box-shadow: 0 0 0 1px var(--orange);
cursor: pointer;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 16px;
}
button {
min-height: 37px;
border: 1px solid var(--line);
border-radius: 10px;
color: #dce8ef;
background: rgba(255, 255, 255, 0.045);
font: inherit;
font-size: 10px;
font-weight: 750;
letter-spacing: 0.04em;
cursor: pointer;
transition: background 150ms ease, transform 150ms ease;
}
button:hover {
background: rgba(255, 255, 255, 0.09);
}
button:active {
transform: translateY(1px);
}
button.primary {
border-color: rgba(85, 230, 213, 0.35);
color: #09201e;
background: var(--cyan);
}
button.primary:hover {
background: #75eee1;
}
.hint {
position: fixed;
bottom: 19px;
left: 25px;
color: rgba(205, 220, 231, 0.68);
font-size: 10px;
letter-spacing: 0.03em;
pointer-events: none;
}
.hint b {
color: var(--cyan);
font-weight: 700;
}
@media (max-width: 700px) {
.brand {
top: 16px;
left: 17px;
}
.brand p {
display: none;
}
.panel {
top: auto;
right: 14px;
bottom: 14px;
max-height: calc(100vh - 92px);
overflow: auto;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="brand">
<div class="eyebrow">Interactive Physics</div>
<h1>Valley Energy</h1>
<p>Frictionless motion · conservation of mechanical energy</p>
</header>
<aside class="panel">
<div class="panel-header">
<strong>Ideal Energy Model</strong>
<div id="status" class="status">In motion</div>
</div>
<div class="formula">
v = √(2g(h₀ − h))
<small>Mass-independent speed</small>
</div>
<div class="metrics">
<div class="metric">
<span>Height</span>
<strong><span id="heightValue">0.00</span><em>m</em></strong>
</div>
<div class="metric">
<span>Speed</span>
<strong><span id="speedValue">0.00</span><em>m/s</em></strong>
</div>
<div class="metric">
<span>Kinetic</span>
<strong><span id="kineticValue">0.00</span><em>J</em></strong>
</div>
<div class="metric">
<span>Potential</span>
<strong><span id="potentialValue">0.00</span><em>J</em></strong>
</div>
</div>
<div class="energy">
<div class="energy-heading">
<span>Mechanical energy</span>
<b id="totalValue">0.00 J</b>
</div>
<div class="bar-row">
<span>KE</span>
<div class="bar"><div id="keBar"></div></div>
<output id="keText">0.00 J</output>
</div>
<div class="bar-row">
<span>PE</span>
<div class="bar"><div id="peBar"></div></div>
<output id="peText">0.00 J</output>
</div>
</div>
<div class="release">
<label for="releaseHeight">
Release height
<output id="releaseValue">2.80 m</output>
</label>
<input
id="releaseHeight"
type="range"
min="1.2"
max="4.15"
step="0.05"
value="2.8"
>
</div>
<div class="buttons">
<button id="toggleButton" class="primary" type="button">Pause</button>
<button id="resetButton" type="button">Restart</button>
<button id="cameraButton" type="button" style="grid-column: 1 / -1">
Reset camera
</button>
</div>
</aside>
<div class="hint">
<b>Drag</b> to orbit · <b>Scroll</b> to zoom · <b>Double-click</b> to reset view
</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Constants and model
// ------------------------------------------------------------
const G = 9.81;
const MASS = 1;
const BOTTOM_Y = 0.45;
const TRACK_X = 5;
const TRACK_WIDTH = 1.28;
const TRACK_THICKNESS = 0.18;
const BALL_RADIUS = 0.23;
const FIXED_DT = 1 / 240;
// Height above the bottom of the valley.
function heightAt(x) {
return 0.105 * x * x + 0.0028 * x ** 4;
}
function slopeAt(x) {
return 0.21 * x + 0.0112 * x ** 3;
}
function worldYAt(x) {
return BOTTOM_Y + heightAt(x);
}
// Invert the monotonic height profile for x >= 0.
function xForHeight(height) {
let low = 0;
let high = TRACK_X;
for (let i = 0; i < 40; i++) {
const mid = (low + high) * 0.5;
if (heightAt(mid) < height) low = mid;
else high = mid;
}
return (low + high) * 0.5;
}
// ------------------------------------------------------------
// Renderer, scene and camera
// ------------------------------------------------------------
const container = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
container.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08111d);
scene.fog = new THREE.Fog(0x08111d, 18, 36);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraState = {
yaw: 0.48,
pitch: 0.29,
distance: 15.8,
target: new THREE.Vector3(-0.25, 1.85, 0)
};
function updateCamera() {
const { yaw, pitch, distance, target } = cameraState;
const horizontal = Math.cos(pitch) * distance;
camera.position.set(
target.x + Math.sin(yaw) * horizontal,
target.y + Math.sin(pitch) * distance,
target.z + Math.cos(yaw) * horizontal
);
camera.lookAt(target);
}
updateCamera();
// ------------------------------------------------------------
// Lighting
// ------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xb5e8ff, 0x172033, 2.1));
const keyLight = new THREE.DirectionalLight(0xffe7c2, 3.1);
keyLight.position.set(-4, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 9;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 25;
keyLight.shadow.bias = -0.0003;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x43d8d0, 20, 16, 2);
rimLight.position.set(4, 3, -4);
scene.add(rimLight);
// ------------------------------------------------------------
// Ground and grid
// ------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(36, 24),
new THREE.MeshStandardMaterial({
color: 0x0b1723,
roughness: 0.96,
metalness: 0.02
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.025;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(24, 48, 0x315064, 0x1b3445);
grid.position.y = -0.015;
grid.material.transparent = true;
grid.material.opacity = 0.34;
scene.add(grid);
// ------------------------------------------------------------
// Track geometry
// ------------------------------------------------------------
const trackGroup = new THREE.Group();
scene.add(trackGroup);
const segments = 72;
const halfWidth = TRACK_WIDTH * 0.5;
const topPositions = [];
const topIndices = [];
for (let i = 0; i <= segments; i++) {
const x = -TRACK_X + (2 * TRACK_X * i) / segments;
const y = worldYAt(x);
topPositions.push(x, y, -halfWidth);
topPositions.push(x, y, halfWidth);
}
for (let i = 0; i < segments; i++) {
const a = i * 2;
const b = a + 1;
const c = a + 2;
const d = a + 3;
topIndices.push(a, b, c, b, d, c);
}
const topGeometry = new THREE.BufferGeometry();
topGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(topPositions, 3)
);
topGeometry.setIndex(topIndices);
topGeometry.computeVertexNormals();
const topMaterial = new THREE.MeshStandardMaterial({
color: 0x176c78,
roughness: 0.8,
metalness: 0.08,
flatShading: true,
side: THREE.DoubleSide
});
const trackTop = new THREE.Mesh(topGeometry, topMaterial);
trackTop.castShadow = true;
trackTop.receiveShadow = true;
trackGroup.add(trackTop);
// Side walls and underside.
const shellPositions = [];
const shellIndices = [];
for (let i = 0; i < segments; i++) {
const x0 = -TRACK_X + (2 * TRACK_X * i) / segments;
const x1 = -TRACK_X + (2 * TRACK_X * (i + 1)) / segments;
const y0 = worldYAt(x0);
const y1 = worldYAt(x1);
for (const z of [-halfWidth, halfWidth]) {
const base = shellPositions.length / 3;
shellPositions.push(
x0, y0, z,
x1, y1, z,
x0, y0 - TRACK_THICKNESS, z,
x1, y1 - TRACK_THICKNESS, z
);
shellIndices.push(
base, base + 1, base + 2,
base + 1, base + 3, base + 2
);
}
const underside = shellPositions.length / 3;
shellPositions.push(
x0, y0 - TRACK_THICKNESS, -halfWidth,
x0, y0 - TRACK_THICKNESS, halfWidth,
x1, y1 - TRACK_THICKNESS, -halfWidth,
x1, y1 - TRACK_THICKNESS, halfWidth
);
shellIndices.push(
underside, underside + 1, underside + 2,
underside + 1, underside + 3, underside + 2
);
}
const shellGeometry = new THREE.BufferGeometry();
shellGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(shellPositions, 3)
);
shellGeometry.setIndex(shellIndices);
shellGeometry.computeVertexNormals();
const shell = new THREE.Mesh(
shellGeometry,
new THREE.MeshStandardMaterial({
color: 0x113b49,
roughness: 0.88,
metalness: 0.12,
flatShading: true,
side: THREE.DoubleSide
})
);
shell.castShadow = true;
shell.receiveShadow = true;
trackGroup.add(shell);
// End caps.
const capPositions = [];
const capIndices = [];
for (const x of [-TRACK_X, TRACK_X]) {
const y = worldYAt(x);
const base = capPositions.length / 3;
capPositions.push(
x, y, -halfWidth,
x, y, halfWidth,
x, y - TRACK_THICKNESS, -halfWidth,
x, y - TRACK_THICKNESS, halfWidth
);
capIndices.push(
base, base + 2, base + 1,
base + 1, base + 2, base + 3
);
}
const capGeometry = new THREE.BufferGeometry();
capGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(capPositions, 3)
);
capGeometry.setIndex(capIndices);
capGeometry.computeVertexNormals();
trackGroup.add(
new THREE.Mesh(
capGeometry,
new THREE.MeshStandardMaterial({
color: 0x164654,
roughness: 0.85,
side: THREE.DoubleSide
})
)
);
// Bright edge rails.
for (const z of [-halfWidth, halfWidth]) {
const points = [];
for (let i = 0; i <= 90; i++) {
const x = -TRACK_X + (2 * TRACK_X * i) / 90;
points.push(new THREE.Vector3(x, worldYAt(x) + 0.025, z));
}
const curve = new THREE.CatmullRomCurve3(points);
const rail = new THREE.Mesh(
new THREE.TubeGeometry(curve, 120, 0.026, 5, false),
new THREE.MeshStandardMaterial({
color: 0x45b9b6,
emissive: 0x123b3b,
emissiveIntensity: 0.65,
roughness: 0.48
})
);
trackGroup.add(rail);
}
// Dashed center guide.
const guidePoints = [];
for (let i = 0; i <= 120; i++) {
const x = -TRACK_X + (2 * TRACK_X * i) / 120;
guidePoints.push(new THREE.Vector3(x, worldYAt(x) + 0.012, 0));
}
const guideGeometry = new THREE.BufferGeometry().setFromPoints(guidePoints);
const guide = new THREE.Line(
guideGeometry,
new THREE.LineDashedMaterial({
color: 0x77b8bc,
transparent: true,
opacity: 0.42,
dashSize: 0.13,
gapSize: 0.12
})
);
guide.computeLineDistances();
trackGroup.add(guide);
// Supports under the track.
const supportMaterial = new THREE.MeshStandardMaterial({
color: 0x152a38,
roughness: 0.82,
metalness: 0.2
});
for (const x of [-4.5, -3.5, -2.5, -1.5, 0, 1.5, 2.5, 3.5, 4.5]) {
const supportHeight = worldYAt(x) - TRACK_THICKNESS;
const support = new THREE.Mesh(
new THREE.BoxGeometry(0.11, supportHeight, 0.18),
supportMaterial
);
support.position.set(x, supportHeight * 0.5, 0);
support.castShadow = true;
support.receiveShadow = true;
trackGroup.add(support);
}
// ------------------------------------------------------------
// Low-poly ball
// ------------------------------------------------------------
let ballGeometry = new THREE.IcosahedronGeometry(BALL_RADIUS, 1);
if (ballGeometry.index) ballGeometry = ballGeometry.toNonIndexed();
const ballPositions = ballGeometry.getAttribute("position");
const ballColors = [];
const palette = [
new THREE.Color(0xffa33d),
new THREE.Color(0xffbd59),
new THREE.Color(0xf08a2d),
new THREE.Color(0xffcf72)
];
for (let i = 0; i < ballPositions.count; i += 3) {
const color = palette[(i / 3) % palette.length];
for (let j = 0; j < 3; j++) {
ballColors.push(color.r, color.g, color.b);
}
}
ballGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(ballColors, 3)
);
ballGeometry.computeVertexNormals();
const ball = new THREE.Mesh(
ballGeometry,
new THREE.MeshStandardMaterial({
vertexColors: true,
roughness: 0.38,
metalness: 0.04,
flatShading: true
})
);
ball.castShadow = true;
ball.receiveShadow = true;
scene.add(ball);
// Ball trail.
const trailPoints = [];
const trailGeometry = new THREE.BufferGeometry();
const trailPositionAttribute = new THREE.BufferAttribute(
new Float32Array(240 * 3),
3
);
trailPositionAttribute.setUsage(THREE.DynamicDrawUsage);
trailGeometry.setAttribute("position", trailPositionAttribute);
trailGeometry.setDrawRange(0, 0);
const trail = new THREE.Line(
trailGeometry,
new THREE.LineBasicMaterial({
color: 0xffb454,
transparent: true,
opacity: 0.3
})
);
trail.frustumCulled = false;
scene.add(trail);
// ------------------------------------------------------------
// Height ruler and measurement guide
// ------------------------------------------------------------
const rulerX = -6.25;
const rulerTop = 4.5;
const rulerPositions = [];
const rulerTicks = [];
rulerTicks.push(rulerX, BOTTOM_Y, 0, rulerX, BOTTOM_Y + rulerTop, 0);
for (let h = 0; h <= rulerTop + 0.001; h += 0.25) {
const isMajor = Math.abs(h - Math.round(h)) < 0.001;
const isMedium = Math.abs(h * 2 - Math.round(h * 2)) < 0.001;
const length = isMajor ? 0.29 : isMedium ? 0.19 : 0.105;
rulerTicks.push(
rulerX, BOTTOM_Y + h, 0,
rulerX - length, BOTTOM_Y + h, 0
);
}
const rulerGeometry = new THREE.BufferGeometry();
rulerGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(rulerTicks, 3)
);
const ruler = new THREE.LineSegments(
rulerGeometry,
new THREE.LineBasicMaterial({
color: 0xb5cad6,
transparent: true,
opacity: 0.82
})
);
scene.add(ruler);
function makeLabel(text, width = 0.68) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 80;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "#c8dbe5";
context.font = "600 34px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2, canvas.height / 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(width, width * 0.3125, 1);
sprite.renderOrder = 10;
return sprite;
}
for (let h = 0; h <= rulerTop + 0.001; h += 1) {
const label = makeLabel(`${h} m`, 0.62);
label.position.set(rulerX - 0.58, BOTTOM_Y + h, 0);
scene.add(label);
}
const rulerTitle = makeLabel("HEIGHT", 0.93);
rulerTitle.position.set(rulerX - 0.04, BOTTOM_Y + rulerTop + 0.32, 0);
scene.add(rulerTitle);
const heightMarker = new THREE.Mesh(
new THREE.OctahedronGeometry(0.075),
new THREE.MeshStandardMaterial({
color: 0xffb454,
emissive: 0x7a3b08,
emissiveIntensity: 0.75,
roughness: 0.35
})
);
scene.add(heightMarker);
const guideLineGeometry = new THREE.BufferGeometry();
guideLineGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(new Float32Array(6), 3)
);
const heightGuide = new THREE.Line(
guideLineGeometry,
new THREE.LineDashedMaterial({
color: 0xffb454,
transparent: true,
opacity: 0.48,
dashSize: 0.12,
gapSize: 0.09
})
);
heightGuide.frustumCulled = false;
scene.add(heightGuide);
// ------------------------------------------------------------
// Simulation state
// ------------------------------------------------------------
const releaseSlider = document.querySelector("#releaseHeight");
const releaseValue = document.querySelector("#releaseValue");
const toggleButton = document.querySelector("#toggleButton");
const resetButton = document.querySelector("#resetButton");
const cameraButton = document.querySelector("#cameraButton");
const status = document.querySelector("#status");
const heightValue = document.querySelector("#heightValue");
const speedValue = document.querySelector("#speedValue");
const kineticValue = document.querySelector("#kineticValue");
const potentialValue = document.querySelector("#potentialValue");
const totalValue = document.querySelector("#totalValue");
const keBar = document.querySelector("#keBar");
const peBar = document.querySelector("#peBar");
const keText = document.querySelector("#keText");
const peText = document.querySelector("#peText");
const simulation = {
x: 0,
v: 0,
running: true,
releaseHeight: Number(releaseSlider.value),
elapsed: 0
};
function resetSimulation() {
simulation.releaseHeight = Number(releaseSlider.value);
simulation.x = -xForHeight(simulation.releaseHeight);
simulation.v = 0;
simulation.elapsed = 0;
simulation.running = true;
trailPoints.length = 0;
trailGeometry.setDrawRange(0, 0);
toggleButton.textContent = "Pause";
status.textContent = "In motion";
status.classList.remove("paused");
}
// Tangential acceleration dv/dt for a particle constrained to y = h(x).
function tangentialAcceleration(x) {
const slope = slopeAt(x);
return (-G * slope) / Math.sqrt(1 + slope * slope);
}
function stepSimulation(dt) {
if (!simulation.running) return;
// Velocity Verlet integration along the curved track.
const a0 = tangentialAcceleration(simulation.x);
simulation.v += 0.5 * a0 * dt;
const slope = slopeAt(simulation.x);
simulation.x += (simulation.v * dt) / Math.sqrt(1 + slope * slope);
const a1 = tangentialAcceleration(simulation.x);
simulation.v += 0.5 * a1 * dt;
simulation.elapsed += dt;
}
function updateRangeFill() {
const min = Number(releaseSlider.min);
const max = Number(releaseSlider.max);
const value = Number(releaseSlider.value);
const percent = 100 * (value - min) / (max - min);
releaseSlider.style.background = `linear-gradient(
to right,
var(--orange) 0%,
var(--orange) ${percent}%,
rgba(255,255,255,0.1) ${percent}%,
rgba(255,255,255,0.1) 100%
)`;
}
releaseSlider.addEventListener("input", () => {
releaseValue.textContent = `${Number(releaseSlider.value).toFixed(2)} m`;
updateRangeFill();
resetSimulation();
});
toggleButton.addEventListener("click", () => {
simulation.running = !simulation.running;
if (simulation.running) {
toggleButton.textContent = "Pause";
status.textContent = "In motion";
status.classList.remove("paused");
} else {
toggleButton.textContent = "Resume";
status.textContent = "Paused";
status.classList.add("paused");
}
});
resetButton.addEventListener("click", resetSimulation);
function resetCamera() {
cameraState.yaw = 0.48;
cameraState.pitch = 0.29;
cameraState.distance = 15.8;
cameraState.target.set(-0.25, 1.85, 0);
updateCamera();
}
cameraButton.addEventListener("click", resetCamera);
// ------------------------------------------------------------
// Direct camera controls: drag to orbit, wheel to zoom
// ------------------------------------------------------------
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.08,
1.12
);
updateCamera();
});
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.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.012,
9,
26
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
// ------------------------------------------------------------
// UI and scene updates
// ------------------------------------------------------------
let uiTimer = 0;
function updateUI() {
const height = heightAt(simulation.x);
const idealSpeed = Math.sqrt(
Math.max(0, 2 * G * (simulation.releaseHeight - height))
);
const kinetic = 0.5 * MASS * idealSpeed * idealSpeed;
const potential = MASS * G * height;
const total = kinetic + potential;
const totalScale = Math.max(total, 0.001);
heightValue.textContent = height.toFixed(2);
speedValue.textContent = idealSpeed.toFixed(2);
kineticValue.textContent = kinetic.toFixed(2);
potentialValue.textContent = potential.toFixed(2);
totalValue.textContent = `${total.toFixed(2)} J`;
keBar.style.width = `${(kinetic / totalScale) * 100}%`;
peBar.style.width = `${(potential / totalScale) * 100}%`;
keText.textContent = `${kinetic.toFixed(2)} J`;
peText.textContent = `${potential.toFixed(2)} J`;
}
function updateTrail() {
const point = new THREE.Vector3(
simulation.x,
worldYAt(simulation.x) + 0.035,
0
);
const last = trailPoints[trailPoints.length - 1];
if (!last || last.distanceToSquared(point) > 0.0025) {
trailPoints.push(point);
}
if (trailPoints.length > 240) trailPoints.shift();
const array = trailPositionAttribute.array;
for (let i = 0; i < trailPoints.length; i++) {
array[i * 3] = trailPoints[i].x;
array[i * 3 + 1] = trailPoints[i].y;
array[i * 3 + 2] = trailPoints[i].z;
}
trailPositionAttribute.needsUpdate = true;
trailGeometry.setDrawRange(0, trailPoints.length);
}
function updateHeightGuide() {
const surfaceY = worldYAt(simulation.x);
heightMarker.position.set(rulerX, surfaceY, 0);
const positions = guideLineGeometry.getAttribute("position");
positions.setXYZ(0, rulerX, surfaceY, 0);
positions.setXYZ(1, simulation.x, surfaceY, 0);
positions.needsUpdate = true;
heightGuide.computeLineDistances();
}
// ------------------------------------------------------------
// Main loop
// ------------------------------------------------------------
const clock = new THREE.Clock();
let accumulator = 0;
function animate() {
const frameTime = Math.min(clock.getDelta(), 0.05);
accumulator += frameTime;
while (accumulator >= FIXED_DT) {
stepSimulation(FIXED_DT);
accumulator -= FIXED_DT;
}
const surfaceY = worldYAt(simulation.x);
ball.position.set(simulation.x, surfaceY + BALL_RADIUS, 0);
// Roll around the Z axis as the ball travels along X.
ball.rotation.z -= (simulation.v * frameTime) / BALL_RADIUS;
updateTrail();
updateHeightGuide();
uiTimer += frameTime;
if (uiTimer > 0.07) {
updateUI();
uiTimer = 0;
}
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
releaseValue.textContent = `${Number(releaseSlider.value).toFixed(2)} m`;
updateRangeFill();
resetSimulation();
updateUI();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```