Prompt specification
Build or customize the Three.js 3D scene "Mass Ratio Changes the Collision" 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: Mass Ratio Changes the Collision
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/mass-ratio-changes-the-collision-x3616
Scene Description Prompt:
Vary masses of fixed-size low-poly discs; compare ideal collision momentum and energy under stated assumptions. Standalone HTML with Three.js from cdnjs.
Working Three.js Starter (mass-ratio-changes-the-collision-x3616):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Impact Lab — Elastic Collision Simulator</title>
<style>
:root {
color-scheme: dark;
--bg: #080c14;
--panel: rgba(15, 21, 34, 0.92);
--panel-2: rgba(20, 28, 44, 0.76);
--border: rgba(157, 180, 214, 0.16);
--text: #edf4ff;
--muted: #8f9db5;
--cyan: #4bd8ff;
--amber: #ffb454;
--green: #72efba;
--red: #ff7082;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
min-height: 100%;
margin: 0;
}
body {
overflow: hidden;
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
background:
radial-gradient(circle at 72% 12%, rgba(39, 94, 140, 0.18), transparent 34%),
radial-gradient(circle at 18% 90%, rgba(64, 46, 107, 0.12), transparent 30%),
var(--bg);
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
.app {
width: 100%;
height: 100vh;
}
.topbar {
height: 70px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 22px;
border-bottom: 1px solid var(--border);
background: rgba(8, 12, 20, 0.82);
backdrop-filter: blur(16px);
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 37px;
height: 37px;
position: relative;
flex: 0 0 auto;
}
.brand-mark::before,
.brand-mark::after {
content: "";
position: absolute;
top: 50%;
width: 23px;
height: 23px;
border: 2px solid;
border-radius: 50%;
transform: translateY(-50%);
}
.brand-mark::before {
left: 0;
border-color: var(--cyan);
box-shadow: 0 0 18px rgba(75, 216, 255, 0.25);
}
.brand-mark::after {
right: 0;
border-color: var(--amber);
box-shadow: 0 0 18px rgba(255, 180, 84, 0.22);
}
.brand h1 {
margin: 0;
font-size: 18px;
line-height: 1.1;
letter-spacing: 0.12em;
}
.brand p {
margin: 4px 0 0;
color: var(--muted);
font-size: 11px;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.top-status {
display: flex;
align-items: center;
gap: 9px;
color: var(--green);
font: 700 11px var(--mono);
letter-spacing: 0.1em;
white-space: nowrap;
}
.status-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 12px var(--green);
}
.layout {
height: calc(100vh - 70px);
display: grid;
grid-template-columns: 304px minmax(0, 1fr);
min-height: 0;
}
.controls {
overflow: auto;
padding: 20px;
border-right: 1px solid var(--border);
background: rgba(10, 15, 25, 0.72);
}
.section-label {
margin: 0 0 12px;
color: var(--muted);
font: 700 10px var(--mono);
letter-spacing: 0.18em;
text-transform: uppercase;
}
.control-group {
margin-bottom: 22px;
}
.control-row {
margin-bottom: 17px;
}
.control-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
font-size: 12px;
}
.control-title span:first-child {
display: flex;
align-items: center;
gap: 8px;
color: #c9d3e3;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.dot.a {
color: var(--cyan);
}
.dot.b {
color: var(--amber);
}
output {
color: var(--text);
font: 700 12px var(--mono);
}
input[type="range"] {
width: 100%;
height: 4px;
display: block;
margin: 0;
border-radius: 999px;
appearance: none;
background: #283248;
cursor: pointer;
accent-color: var(--cyan);
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
appearance: none;
border: 2px solid #0b111c;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 1px rgba(75, 216, 255, 0.3);
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 2px solid #0b111c;
border-radius: 50%;
background: var(--cyan);
}
#mB::-webkit-slider-thumb,
#vB::-webkit-slider-thumb {
background: var(--amber);
}
#mB::-moz-range-thumb,
#vB::-moz-range-thumb {
background: var(--amber);
}
.range-limits {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: #647188;
font: 9px var(--mono);
}
.hint {
margin: -4px 0 16px;
color: #75839a;
font-size: 10px;
line-height: 1.55;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 8px;
}
button {
min-height: 38px;
border: 1px solid var(--border);
border-radius: 8px;
background: rgba(35, 47, 70, 0.56);
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
button:hover {
border-color: rgba(75, 216, 255, 0.45);
background: rgba(44, 62, 91, 0.8);
}
button:active {
transform: translateY(1px);
}
.primary {
border-color: rgba(75, 216, 255, 0.45);
color: #dff8ff;
background: rgba(35, 130, 166, 0.3);
font-weight: 700;
}
.presets {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.presets button {
min-height: 32px;
color: #aebbd0;
font: 600 10px var(--mono);
}
.camera-help {
padding: 13px;
border: 1px solid var(--border);
border-radius: 10px;
color: #8492a8;
background: rgba(23, 31, 48, 0.45);
font-size: 11px;
line-height: 1.55;
}
.camera-help strong {
display: block;
margin-bottom: 4px;
color: #c4cede;
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.workspace {
min-width: 0;
min-height: 0;
display: grid;
grid-template-rows: minmax(360px, 1fr) auto;
}
.stage {
position: relative;
min-height: 0;
overflow: hidden;
border-bottom: 1px solid var(--border);
background:
radial-gradient(circle at 50% 42%, rgba(32, 66, 99, 0.18), transparent 40%),
#080d16;
}
#canvasHost {
position: absolute;
inset: 0;
}
#canvasHost canvas {
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#canvasHost canvas:active {
cursor: grabbing;
}
.stage-top {
position: absolute;
top: 16px;
left: 18px;
right: 18px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
pointer-events: none;
}
.geometry-badge,
.conservation-chip,
.phase-badge {
border: 1px solid var(--border);
border-radius: 9px;
background: rgba(8, 13, 22, 0.72);
backdrop-filter: blur(10px);
}
.geometry-badge {
padding: 9px 11px;
color: #aab8cd;
font: 600 10px var(--mono);
letter-spacing: 0.07em;
}
.conservation-chips {
display: flex;
gap: 8px;
flex-wrap: wrap;
justify-content: flex-end;
}
.conservation-chip {
min-width: 120px;
padding: 8px 10px;
}
.conservation-chip span {
display: block;
color: var(--muted);
font: 9px var(--mono);
letter-spacing: 0.08em;
}
.conservation-chip strong {
display: block;
margin-top: 3px;
color: var(--green);
font: 700 12px var(--mono);
}
.stage-bottom {
position: absolute;
right: 18px;
bottom: 15px;
left: 18px;
display: grid;
grid-template-columns: auto 1fr auto;
align-items: center;
gap: 14px;
pointer-events: none;
}
.phase-badge {
min-width: 128px;
padding: 8px 10px;
color: var(--cyan);
font: 700 10px var(--mono);
letter-spacing: 0.1em;
}
.timeline-wrap {
pointer-events: auto;
padding: 8px 12px;
border: 1px solid var(--border);
border-radius: 9px;
background: rgba(8, 13, 22, 0.72);
backdrop-filter: blur(10px);
}
.timeline-wrap input {
height: 3px;
}
.time-readout {
min-width: 70px;
color: #99a7bc;
text-align: right;
font: 10px var(--mono);
}
.reset-camera {
position: absolute;
top: 75px;
right: 18px;
min-height: 30px;
padding: 0 10px;
color: #a8b5c9;
font: 600 10px var(--mono);
background: rgba(8, 13, 22, 0.72);
}
.ledgers {
display: grid;
grid-template-columns: 1fr 1.1fr 1.25fr;
gap: 10px;
padding: 12px;
}
.card {
min-width: 0;
padding: 14px;
border: 1px solid var(--border);
border-radius: 12px;
background: linear-gradient(145deg, rgba(20, 28, 44, 0.88), rgba(13, 19, 31, 0.88));
}
.card-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 10px;
}
.card h2 {
margin: 0;
font-size: 12px;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.conserved {
color: var(--green);
font: 700 8px var(--mono);
letter-spacing: 0.1em;
}
.big-value {
margin-bottom: 10px;
font: 700 23px var(--mono);
}
.big-value small {
margin-left: 5px;
color: var(--muted);
font-size: 9px;
font-weight: 500;
}
.compare-row {
display: grid;
grid-template-columns: 55px 1fr;
align-items: center;
gap: 8px;
margin-top: 7px;
}
.compare-row > span {
color: #6f7d92;
font: 9px var(--mono);
letter-spacing: 0.08em;
}
.value-pair {
display: flex;
justify-content: space-between;
gap: 8px;
color: #bcc8d9;
font: 10px var(--mono);
}
.value-pair b {
color: var(--text);
font-weight: 700;
}
.a-text {
color: var(--cyan);
}
.b-text {
color: var(--amber);
}
.delta {
margin-top: 9px;
padding-top: 8px;
border-top: 1px solid var(--border);
color: #758399;
font: 9px var(--mono);
}
.delta b {
color: var(--green);
}
.stack {
height: 10px;
display: flex;
overflow: hidden;
margin: 5px 0 2px;
border-radius: 999px;
background: #202a3b;
}
.stack span {
height: 100%;
min-width: 0;
transition: width 180ms ease;
}
.bar-a {
background: linear-gradient(90deg, #218eb3, var(--cyan));
}
.bar-b {
background: linear-gradient(90deg, #c47b2e, var(--amber));
}
.energy-labels {
display: flex;
justify-content: space-between;
gap: 8px;
color: #93a0b5;
font: 9px var(--mono);
}
.insight {
margin-top: 11px;
padding: 10px;
border-left: 2px solid var(--cyan);
border-radius: 0 7px 7px 0;
color: #aebbd0;
background: rgba(75, 216, 255, 0.055);
font-size: 10px;
line-height: 1.55;
}
.formula {
margin: 8px 0 0;
color: #b8c5d9;
font: 10px/1.6 var(--mono);
white-space: normal;
}
.formula div + div {
margin-top: 3px;
}
.assumptions {
margin: 11px 0 0;
padding-top: 10px;
border-top: 1px solid var(--border);
color: #7f8da3;
font-size: 10px;
line-height: 1.55;
}
.assumptions strong {
color: #aebbd0;
}
@media (max-width: 1080px) {
.layout {
grid-template-columns: 270px minmax(0, 1fr);
}
.ledgers {
grid-template-columns: 1fr 1fr;
}
.formula-card {
grid-column: 1 / -1;
}
}
@media (max-width: 760px) {
body {
overflow: auto;
}
.app,
.layout {
height: auto;
min-height: 100vh;
}
.topbar {
height: 64px;
padding: 0 14px;
}
.brand p,
.top-status {
display: none;
}
.layout {
display: flex;
flex-direction: column;
}
.controls {
overflow: visible;
border-right: 0;
border-bottom: 1px solid var(--border);
}
.workspace {
display: block;
}
.stage {
height: 62vh;
min-height: 440px;
}
.ledgers {
grid-template-columns: 1fr;
}
.formula-card {
grid-column: auto;
}
.stage-top,
.stage-bottom {
left: 10px;
right: 10px;
}
.geometry-badge {
display: none;
}
.conservation-chip {
min-width: 105px;
}
.phase-badge {
min-width: 100px;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true"></div>
<div>
<h1>IMPACT LAB</h1>
<p>Fixed geometry · variable mass · ideal elastic impact</p>
</div>
</div>
<div class="top-status">
<span class="status-dot"></span>
THREE.JS CORE / REAL-TIME COMPARISON
</div>
</header>
<main class="layout">
<aside class="controls">
<p class="section-label">Experiment parameters</p>
<section class="control-group">
<div class="control-row">
<label class="control-title" for="mA">
<span><i class="dot a"></i>Disk A mass</span>
<output id="mAOut">1.0 kg</output>
</label>
<input id="mA" data-param="mA" type="range" min="0.5" max="8" step="0.1" value="1">
<div class="range-limits"><span>0.5 kg</span><span>8.0 kg</span></div>
</div>
<div class="control-row">
<label class="control-title" for="mB">
<span><i class="dot b"></i>Disk B mass</span>
<output id="mBOut">3.0 kg</output>
</label>
<input id="mB" data-param="mB" type="range" min="0.5" max="8" step="0.1" value="3">
<div class="range-limits"><span>0.5 kg</span><span>8.0 kg</span></div>
</div>
<p class="hint">
Radius and thickness remain fixed. Changing mass is therefore
interpreted as changing the disc material’s density.
</p>
</section>
<p class="section-label">Initial velocities</p>
<section class="control-group">
<div class="control-row">
<label class="control-title" for="vA">
<span><i class="dot a"></i>Disk A velocity</span>
<output id="vAOut">+2.0 m/s</output>
</label>
<input id="vA" data-param="vA" type="range" min="-3.9" max="4" step="0.1" value="2">
<div class="range-limits"><span>−3.9</span><span>+4.0 m/s</span></div>
</div>
<div class="control-row">
<label class="control-title" for="vB">
<span><i class="dot b"></i>Disk B velocity</span>
<output id="vBOut">−2.0 m/s</output>
</label>
<input id="vB" data-param="vB" type="range" min="-4" max="3.9" step="0.1" value="-2">
<div class="range-limits"><span>−4.0</span><span>+3.9 m/s</span></div>
</div>
<p class="hint">
The controls enforce an approaching pair: v<sub>A</sub> > v<sub>B</sub>.
Positive velocity points right.
</p>
</section>
<div class="button-row">
<button id="playBtn" class="primary" type="button">Pause</button>
<button id="resetBtn" type="button">Reset</button>
</div>
<p class="section-label" style="margin-top: 20px">Mass presets</p>
<div class="presets">
<button type="button" data-preset="equal">1 : 1</button>
<button type="button" data-preset="heavyA">3 : 1</button>
<button type="button" data-preset="heavyB">1 : 3</button>
</div>
<p class="section-label" style="margin-top: 22px">Camera</p>
<div class="camera-help">
<strong>Direct controls</strong>
Drag to orbit the scene. Use the mouse wheel to zoom.
No camera-control addons are used.
</div>
</aside>
<section class="workspace">
<div class="stage" id="stage">
<div id="canvasHost"></div>
<div class="stage-top">
<div class="geometry-badge">GEOMETRY LOCKED · r = 0.50 m</div>
<div class="conservation-chips">
<div class="conservation-chip">
<span>TOTAL MOMENTUM</span>
<strong id="hudP">0.00 kg·m/s</strong>
</div>
<div class="conservation-chip">
<span>TOTAL KINETIC ENERGY</span>
<strong id="hudK">0.00 J</strong>
</div>
</div>
</div>
<button id="resetCameraBtn" class="reset-camera" type="button">
RESET VIEW
</button>
<div class="stage-bottom">
<div id="phaseText" class="phase-badge" aria-live="polite">APPROACH</div>
<div class="timeline-wrap">
<input id="timeline" type="range" min="0" max="1000" step="1" value="0"
aria-label="Collision timeline">
</div>
<div id="timeText" class="time-readout">t = 0.00 s</div>
</div>
</div>
<div class="ledgers">
<article class="card">
<div class="card-head">
<h2>Momentum</h2>
<span class="conserved">CONSERVED</span>
</div>
<div class="big-value">
<span id="pTotal">0.00</span><small>kg·m/s</small>
</div>
<div class="compare-row">
<span>BEFORE</span>
<div class="value-pair">
<span class="a-text">A <b id="pBeforeA">0.00</b></span>
<span class="b-text">B <b id="pBeforeB">0.00</b></span>
</div>
</div>
<div class="compare-row">
<span>AFTER</span>
<div class="value-pair">
<span class="a-text">A <b id="pAfterA">0.00</b></span>
<span class="b-text">B <b id="pAfterB">0.00</b></span>
</div>
</div>
<div class="delta">
ΔΣp = <b id="pDelta">0.000000</b>
</div>
</article>
<article class="card">
<div class="card-head">
<h2>Kinetic Energy</h2>
<span class="conserved">CONSERVED</span>
</div>
<div class="big-value">
<span id="kTotal">0.00</span><small>J</small>
</div>
<div class="compare-row">
<span>BEFORE</span>
<div>
<div class="stack">
<span id="barBeforeA" class="bar-a"></span>
<span id="barBeforeB" class="bar-b"></span>
</div>
<div class="energy-labels">
<span class="a-text">A <b id="kBeforeA">0.00</b></span>
<span class="b-text">B <b id="kBeforeB">0.00</b></span>
</div>
</div>
</div>
<div class="compare-row">
<span>AFTER</span>
<div>
<div class="stack">
<span id="barAfterA" class="bar-a"></span>
<span id="barAfterB" class="bar-b"></span>
</div>
<div class="energy-labels">
<span class="a-text">A <b id="kAfterA">0.00</b></span>
<span class="b-text">B <b id="kAfterB">0.00</b></span>
</div>
</div>
</div>
<div class="delta">
ΔΣK = <b id="kDelta">0.000000</b>
</div>
</article>
<article class="card formula-card">
<div class="card-head">
<h2>Ideal 1D Elastic Collision</h2>
<span class="conserved">e = 1.00</span>
</div>
<div class="formula">
<div>v′<sub>A</sub> = [(m<sub>A</sub>−m<sub>B</sub>)u<sub>A</sub> + 2m<sub>B</sub>u<sub>B</sub>] / (m<sub>A</sub>+m<sub>B</sub>)</div>
<div>v′<sub>B</sub> = [2m<sub>A</sub>u<sub>A</sub> + (m<sub>B</sub>−m<sub>A</sub>)u<sub>B</sub>] / (m<sub>A</sub>+m<sub>B</sub>)</div>
<div>Σp = m<sub>A</sub>v<sub>A</sub> + m<sub>B</sub>v<sub>B</sub></div>
<div>ΣK = ½m<sub>A</sub>v<sub>A</sub>² + ½m<sub>B</sub>v<sub>B</sub>²</div>
</div>
<div class="insight" id="insightText"></div>
<p class="assumptions">
<strong>Assumptions:</strong> perfectly head-on one-dimensional motion;
perfectly elastic impact; no friction, deformation, rotation, or external
impulse. The visual radius and thickness are fixed for every mass.
</p>
</article>
</div>
</section>
</main>
</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 params = {
mA: 1,
mB: 3,
vA: 2,
vB: -2
};
const DEFAULTS = { ...params };
const RADIUS = 0.5;
const START_A = -3.4;
const START_B = 3.4;
const COLORS = {
a: 0x4bd8ff,
b: 0xffb454
};
const state = {
time: 0,
duration: 1,
collisionTime: 1,
contactA: 0,
contactB: 0,
contactCenter: 0,
postVA: 0,
postVB: 0,
playing: true,
flashStart: -Infinity
};
// ---------- Three.js scene ----------
const host = $("canvasHost");
const stage = $("stage");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x080d16);
scene.fog = new THREE.Fog(0x080d16, 14, 29);
const camera = new THREE.PerspectiveCamera(42, 1, 0.1, 100);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute(
"aria-label",
"Interactive 3D simulation of two colliding low-poly discs"
);
host.appendChild(renderer.domElement);
scene.add(new THREE.HemisphereLight(0xb9dcff, 0x182033, 2.0));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(-4, 8, 5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -10;
keyLight.shadow.camera.right = 10;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
keyLight.shadow.bias = -0.0005;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4b9cff, 1.4);
rimLight.position.set(6, 3, -6);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 18),
new THREE.MeshStandardMaterial({
color: 0x0b111d,
roughness: 0.93,
metalness: 0.05
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.21;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(24, 24, 0x283b54, 0x111c2c);
grid.position.y = -0.195;
grid.material.transparent = true;
grid.material.opacity = 0.62;
scene.add(grid);
const axisGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(-9, -0.185, 0),
new THREE.Vector3(9, -0.185, 0)
]);
const axis = new THREE.Line(
axisGeometry,
new THREE.LineDashedMaterial({
color: 0x4c6686,
dashSize: 0.22,
gapSize: 0.13,
transparent: true,
opacity: 0.58
})
);
axis.computeLineDistances();
scene.add(axis);
function roundedRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function createLabelSprite(color) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 160;
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(2.25, 0.70, 1);
sprite.renderOrder = 20;
sprite.userData.canvas = canvas;
sprite.userData.texture = texture;
sprite.userData.color = color;
sprite.userData.lastText = "";
return sprite;
}
function updateLabel(sprite, title, subtitle) {
const text = `${title}\n${subtitle}`;
if (sprite.userData.lastText === text) return;
const canvas = sprite.userData.canvas;
const ctx = canvas.getContext("2d");
const cssColor = `#${sprite.userData.color.toString(16).padStart(6, "0")}`;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(7, 12, 21, 0.88)";
ctx.strokeStyle = cssColor;
ctx.lineWidth = 4;
roundedRect(ctx, 10, 10, 492, 140, 22);
ctx.fill();
ctx.stroke();
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = cssColor;
ctx.font = "700 43px ui-monospace, Menlo, Consolas, monospace";
ctx.fillText(title, 256, 57);
ctx.fillStyle = "#dce8f7";
ctx.font = "600 27px ui-monospace, Menlo, Consolas, monospace";
ctx.fillText(subtitle, 256, 111);
sprite.userData.texture.needsUpdate = true;
sprite.userData.lastText = text;
}
function createDisc(color, name) {
const group = new THREE.Group();
const topMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.48,
metalness: 0.18,
flatShading: true
});
const sideMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color(color).multiplyScalar(0.43),
roughness: 0.72,
metalness: 0.12,
flatShading: true
});
const bottomMaterial = new THREE.MeshStandardMaterial({
color: 0x111827,
roughness: 0.8,
metalness: 0.08,
flatShading: true
});
const body = new THREE.Mesh(
new THREE.CylinderGeometry(RADIUS, RADIUS, 0.36, 12, 1, false),
[sideMaterial, topMaterial, bottomMaterial]
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const rim = new THREE.Mesh(
new THREE.TorusGeometry(RADIUS * 0.82, 0.022, 4, 12),
new THREE.MeshStandardMaterial({
color: 0xe9f7ff,
emissive: color,
emissiveIntensity: 0.28,
roughness: 0.35,
metalness: 0.25,
flatShading: true
})
);
rim.rotation.x = Math.PI / 2;
rim.position.y = 0.19;
group.add(rim);
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.13, 0.13, 0.025, 12),
new THREE.MeshStandardMaterial({
color: 0x101827,
roughness: 0.55,
metalness: 0.35,
flatShading: true
})
);
hub.position.y = 0.195;
group.add(hub);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(body.geometry, 18),
new THREE.LineBasicMaterial({
color: 0xd5e7f7,
transparent: true,
opacity: 0.25
})
);
group.add(edges);
const label = createLabelSprite(color);
label.position.set(0, 1.02, 0);
group.add(label);
const arrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(0, 0, 0),
1,
color,
0.22,
0.14
);
arrow.line.material.transparent = true;
arrow.line.material.opacity = 0.95;
arrow.cone.material.transparent = true;
arrow.cone.material.opacity = 0.95;
scene.add(arrow);
scene.add(group);
return { group, label, arrow, name };
}
const discA = createDisc(COLORS.a, "A");
const discB = createDisc(COLORS.b, "B");
const contactRing = new THREE.Mesh(
new THREE.TorusGeometry(0.62, 0.018, 6, 48),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0,
depthWrite: false
})
);
contactRing.rotation.x = Math.PI / 2;
contactRing.position.y = -0.18;
contactRing.visible = false;
scene.add(contactRing);
// ---------- Direct camera controls ----------
const cameraState = {
yaw: 0.42,
pitch: 0.48,
distance: 13.2,
target: new THREE.Vector3(0, 0.2, 0)
};
function updateCamera() {
const cp = Math.cos(cameraState.pitch);
const sp = Math.sin(cameraState.pitch);
camera.position.set(
cameraState.target.x + cameraState.distance * cp * Math.sin(cameraState.yaw),
cameraState.target.y + cameraState.distance * sp,
cameraState.target.z + cameraState.distance * cp * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
}
function resetCamera() {
cameraState.yaw = 0.42;
cameraState.pitch = 0.48;
cameraState.distance = 13.2;
cameraState.target.set(0, 0.2, 0);
updateCamera();
}
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.005,
0.12,
1.18
);
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("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener(
"wheel",
event => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.008,
7.5,
22
);
updateCamera();
},
{ passive: false }
);
$("resetCameraBtn").addEventListener("click", resetCamera);
const resizeObserver = new ResizeObserver(() => {
const width = host.clientWidth;
const height = host.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
});
resizeObserver.observe(stage);
// ---------- Physics and UI ----------
function formatSigned(value, digits = 2) {
if (Math.abs(value) < 1e-9) return (0).toFixed(digits);
return `${value > 0 ? "+" : ""}${value.toFixed(digits)}`;
}
function formatNumber(value, digits = 2) {
if (Math.abs(value) < 0.0000001) return (0).toFixed(digits);
return value.toFixed(digits);
}
function syncControls() {
$("mA").value = params.mA;
$("mB").value = params.mB;
$("vA").value = params.vA;
$("vB").value = params.vB;
$("mAOut").textContent = `${params.mA.toFixed(1)} kg`;
$("mBOut").textContent = `${params.mB.toFixed(1)} kg`;
$("vAOut").textContent = `${formatSigned(params.vA, 1)} m/s`;
$("vBOut").textContent = `${formatSigned(params.vB, 1)} m/s`;
}
function updateEnergyBars(total, a, b, prefix) {
const safeTotal = total > 1e-12 ? total : 1;
$(`bar${prefix}A`).style.width = `${(a / safeTotal) * 100}%`;
$(`bar${prefix}B`).style.width = `${(b / safeTotal) * 100}%`;
}
function recomputeDerived(resetTime = true) {
const { mA, mB, vA, vB } = params;
const relativeVelocity = vA - vB;
const initialGap = START_B - START_A - 2 * RADIUS;
const collisionTime = initialGap / relativeVelocity;
const contactA = START_A + vA * collisionTime;
const contactB = START_B + vB * collisionTime;
const contactCenter = contactA + RADIUS;
const totalMass = mA + mB;
const postVA =
((mA - mB) * vA + 2 * mB * vB) / totalMass;
const postVB =
(2 * mA * vA + (mB - mA) * vB) / totalMass;
const postDuration = THREE.MathUtils.clamp(
6.8 / relativeVelocity,
1.2,
2.5
);
state.collisionTime = collisionTime;
state.contactA = contactA;
state.contactB = contactB;
state.contactCenter = contactCenter;
state.postVA = postVA;
state.postVB = postVB;
state.duration = collisionTime + postDuration;
if (resetTime) {
state.time = 0;
state.flashStart = -Infinity;
contactRing.visible = false;
} else {
state.time = Math.min(state.time, state.duration);
}
const pBeforeA = mA * vA;
const pBeforeB = mB * vB;
const pAfterA = mA * postVA;
const pAfterB = mB * postVB;
const pTotalBefore = pBeforeA + pBeforeB;
const pTotalAfter = pAfterA + pAfterB;
const kBeforeA = 0.5 * mA * vA * vA;
const kBeforeB = 0.5 * mB * vB * vB;
const kAfterA = 0.5 * mA * postVA * postVA;
const kAfterB = 0.5 * mB * postVB * postVB;
const kTotalBefore = kBeforeA + kBeforeB;
const kTotalAfter = kAfterA + kAfterB;
$("pTotal").textContent = formatSigned(pTotalBefore);
$("pBeforeA").textContent = formatSigned(pBeforeA);
$("pBeforeB").textContent = formatSigned(pBeforeB);
$("pAfterA").textContent = formatSigned(pAfterA);
$("pAfterB").textContent = formatSigned(pAfterB);
$("pDelta").textContent = formatSigned(pTotalAfter - pTotalBefore, 6);
$("kTotal").textContent = formatNumber(kTotalBefore);
$("kBeforeA").textContent = formatNumber(kBeforeA);
$("kBeforeB").textContent = formatNumber(kBeforeB);
$("kAfterA").textContent = formatNumber(kAfterA);
$("kAfterB").textContent = formatNumber(kAfterB);
$("kDelta").textContent = formatSigned(kTotalAfter - kTotalBefore, 6);
updateEnergyBars(kTotalBefore, kBeforeA, kBeforeB, "Before");
updateEnergyBars(kTotalAfter, kAfterA, kAfterB, "After");
const heavier = mA > mB ? "A" : mA < mB ? "B" : "neither disc";
const heavierEnergy =
mA > mB ? kAfterA : mA < mB ? kAfterB : (kAfterA + kAfterB) / 2;
const share = kTotalAfter > 1e-12
? (heavierEnergy / kTotalAfter) * 100
: 0;
$("insightText").textContent =
mA === mB
? "With equal masses, the discs exchange velocities. Each retains the same speed magnitude and therefore the same kinetic energy."
: `Disk ${heavier} is heavier and ends with ${share.toFixed(1)}% of the total kinetic energy. Momentum remains balanced across both discs.`;
updatePositions();
}
function updatePositions() {
const t = state.time;
const tc = state.collisionTime;
let xA;
let xB;
let vA;
let vB;
if (t <= tc) {
xA = START_A + params.vA * t;
xB = START_B + params.vB * t;
vA = params.vA;
vB = params.vB;
} else {
const after = t - tc;
xA = state.contactA + state.postVA * after;
xB = state.contactB + state.postVB * after;
vA = state.postVA;
vB = state.postVB;
}
discA.group.position.x = xA;
discB.group.position.x = xB;
const pA = params.mA * vA;
const pB = params.mB * vB;
updateArrow(discA.arrow, xA, pA, COLORS.a);
updateArrow(discB.arrow, xB, pB, COLORS.b);
updateLabel(
discA.label,
`A · ${params.mA.toFixed(1)} kg`,
`v ${formatSigned(vA, 1)} | p ${formatSigned(pA, 1)}`
);
updateLabel(
discB.label,
`B · ${params.mB.toFixed(1)} kg`,
`v ${formatSigned(vB, 1)} | p ${formatSigned(pB, 1)}`
);
let phase = "APPROACH";
if (Math.abs(t - tc) < 0.055) phase = "CONTACT";
else if (t > tc) phase = "SEPARATION";
$("phaseText").textContent = phase;
$("timeText").textContent = `t = ${t.toFixed(2)} s`;
$("hudP").textContent = `${formatSigned(pA + pB)} kg·m/s`;
$("hudK").textContent = `${formatNumber(
0.5 * params.mA * vA * vA + 0.5 * params.mB * vB * vB
)} J`;
}
function updateArrow(arrow, x, momentum, color) {
arrow.visible = Math.abs(momentum) > 0.001;
const direction = new THREE.Vector3(
momentum >= 0 ? 1 : -1,
0,
0
);
arrow.position.set(x, 0.47, 0);
arrow.setDirection(direction);
arrow.setColor(new THREE.Color(color));
const length = THREE.MathUtils.clamp(
0.45 + Math.abs(momentum) * 0.22,
0.45,
3.1
);
arrow.setLength(length, 0.24, 0.15);
}
function updatePlayButton() {
$("playBtn").textContent = state.playing
? "Pause"
: state.time >= state.duration
? "Replay"
: "Play";
}
function togglePlayback() {
if (!state.playing && state.time >= state.duration) {
state.time = 0;
state.flashStart = -Infinity;
}
state.playing = !state.playing;
updatePlayButton();
}
$("playBtn").addEventListener("click", togglePlayback);
$("resetBtn").addEventListener("click", () => {
Object.assign(params, DEFAULTS);
syncControls();
recomputeDerived(true);
state.playing = true;
updatePlayButton();
});
document.querySelectorAll("[data-param]").forEach(input => {
input.addEventListener("input", event => {
const key = event.target.dataset.param;
params[key] = Number(event.target.value);
// Keep the pair approaching in one dimension.
if (params.vA <= params.vB) {
if (key === "vA") {
params.vA = Math.min(4, params.vB + 0.1);
} else {
params.vB = Math.max(-3.9, params.vA - 0.1);
}
// Boundary fallback if both constraints meet.
if (params.vA <= params.vB) {
params.vA = 3.9;
params.vB = -3.9;
}
}
syncControls();
recomputeDerived(true);
});
});
document.querySelectorAll("[data-preset]").forEach(button => {
button.addEventListener("click", () => {
const preset = button.dataset.preset;
if (preset === "equal") {
params.mA = 1;
params.mB = 1;
} else if (preset === "heavyA") {
params.mA = 3;
params.mB = 1;
} else {
params.mA = 1;
params.mB = 3;
}
syncControls();
recomputeDerived(true);
});
});
$("timeline").addEventListener("input", event => {
state.time = (Number(event.target.value) / 1000) * state.duration;
state.playing = false;
updatePlayButton();
updatePositions();
});
// ---------- Animation ----------
const clock = new THREE.Clock();
function triggerCollisionFlash() {
state.flashStart = performance.now();
contactRing.position.x = state.contactCenter;
contactRing.visible = true;
}
function animate(now) {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
const previousTime = state.time;
if (state.playing) {
state.time += dt;
if (
previousTime < state.collisionTime &&
state.time >= state.collisionTime
) {
triggerCollisionFlash();
}
if (state.time >= state.duration) {
state.time = state.duration;
state.playing = false;
updatePlayButton();
}
}
updatePositions();
$("timeline").value = String(
Math.round((state.time / state.duration) * 1000)
);
const flashAge = (now - state.flashStart) / 1000;
if (flashAge >= 0 && flashAge < 0.65) {
contactRing.visible = true;
contactRing.material.opacity = Math.max(0, 1 - flashAge / 0.65);
const scale = 0.75 + flashAge * 2.8;
contactRing.scale.set(scale, scale, scale);
} else {
contactRing.visible = false;
}
renderer.render(scene, camera);
}
syncControls();
recomputeDerived(true);
resetCamera();
updatePlayButton();
requestAnimationFrame(animate);
</script>
</body>
</html>
```