Prompt specification
Build or customize the Three.js 3D scene "Elastic and sticking collision comparison" 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: Elastic and sticking collision comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/elastic-and-sticking-collision-comparison-x1370
Scene Description Prompt:
Create a standalone stylized scene in one HTML file using Three.js from cdnjs. Run matched one-dimensional collisions with restitution one and zero; display total momentum in both cases and distinguish kinetic energy loss from momentum change.
Working Three.js Starter (elastic-and-sticking-collision-comparison-x1370):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>1D Collision Lab — Momentum vs. Kinetic Energy</title>
<style>
:root {
color-scheme: dark;
--bg: #070b14;
--panel: #0c1220;
--panel-2: #111a2b;
--border: rgba(164, 190, 226, 0.14);
--text: #edf4ff;
--muted: #92a3bd;
--cyan: #49b8ff;
--pink: #ff6b8b;
--green: #58e1ad;
--orange: #ffb45b;
--purple: #a98bff;
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
width: 100%;
height: 100%;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
body {
overflow: hidden;
}
button,
input,
select {
font: inherit;
}
button {
color: var(--text);
}
#app {
display: flex;
width: 100%;
height: 100dvh;
}
#stage {
position: relative;
flex: 1;
min-width: 0;
overflow: hidden;
background:
radial-gradient(circle at 35% 20%, rgba(61, 110, 168, 0.13), transparent 38%),
#070b14;
}
#stage canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active {
cursor: grabbing;
}
.hero {
position: absolute;
z-index: 3;
top: 24px;
left: 26px;
right: 24px;
pointer-events: none;
}
.eyebrow {
display: inline-flex;
align-items: center;
gap: 8px;
margin-bottom: 10px;
color: #a8bddb;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 16px var(--green);
content: "";
}
h1 {
margin: 0;
max-width: 760px;
font-size: clamp(26px, 3.3vw, 48px);
line-height: 1.03;
letter-spacing: -0.045em;
}
.subtitle {
max-width: 690px;
margin: 12px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.phase {
display: inline-flex;
align-items: center;
gap: 8px;
margin-top: 14px;
padding: 7px 10px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(8, 14, 26, 0.72);
color: #c4d2e7;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
backdrop-filter: blur(10px);
}
.phase span {
width: 6px;
height: 6px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
.view-hint {
position: absolute;
z-index: 3;
right: 22px;
bottom: 118px;
color: rgba(185, 202, 228, 0.65);
font-size: 10px;
letter-spacing: 0.04em;
pointer-events: none;
}
.transport {
position: absolute;
z-index: 4;
right: 22px;
bottom: 20px;
left: 22px;
padding: 14px 16px;
border: 1px solid var(--border);
border-radius: 16px;
background: rgba(9, 15, 28, 0.86);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(18px);
}
.transport-top {
display: flex;
align-items: center;
gap: 9px;
}
.control-button {
min-height: 34px;
padding: 0 13px;
border: 1px solid rgba(166, 194, 229, 0.17);
border-radius: 9px;
background: #151f32;
cursor: pointer;
font-size: 11px;
font-weight: 750;
transition: border-color 150ms, background 150ms, transform 150ms;
}
.control-button:hover {
border-color: rgba(166, 194, 229, 0.35);
background: #1b2940;
}
.control-button:active {
transform: translateY(1px);
}
.control-button.primary {
border-color: rgba(73, 184, 255, 0.35);
background: rgba(73, 184, 255, 0.14);
color: #bfe7ff;
}
.time-readout {
margin-left: auto;
color: #b9c8dd;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
white-space: nowrap;
}
.timeline-wrap {
position: relative;
margin-top: 13px;
}
#timeline {
display: block;
width: 100%;
height: 4px;
margin: 0;
border-radius: 999px;
outline: none;
appearance: none;
background:
linear-gradient(
to right,
var(--cyan) 0 var(--progress, 0%),
#253149 var(--progress, 0%) 100%
);
cursor: pointer;
}
#timeline::-webkit-slider-thumb {
width: 14px;
height: 14px;
border: 2px solid #dff5ff;
border-radius: 50%;
appearance: none;
background: var(--cyan);
box-shadow: 0 0 14px rgba(73, 184, 255, 0.7);
}
#timeline::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid #dff5ff;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 14px rgba(73, 184, 255, 0.7);
}
.impact-marker {
position: absolute;
top: -5px;
left: 37.5%;
width: 1px;
height: 14px;
background: var(--orange);
box-shadow: 0 0 8px rgba(255, 180, 91, 0.65);
pointer-events: none;
}
.impact-label {
position: absolute;
top: 12px;
left: 37.5%;
transform: translateX(-50%);
color: #d7a968;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
pointer-events: none;
}
#panel {
width: 380px;
flex: 0 0 380px;
overflow-y: auto;
padding: 24px 20px 28px;
border-left: 1px solid var(--border);
background:
linear-gradient(180deg, rgba(18, 28, 47, 0.64), transparent 220px),
var(--panel);
scrollbar-width: thin;
scrollbar-color: #293752 transparent;
}
.panel-title {
margin: 0;
font-size: 17px;
letter-spacing: -0.02em;
}
.panel-copy {
margin: 7px 0 18px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.setup {
margin-bottom: 16px;
padding: 14px;
border: 1px solid var(--border);
border-radius: 13px;
background: rgba(18, 29, 48, 0.6);
}
.setup-heading {
margin-bottom: 11px;
color: #9fb0c9;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.setup-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 9px;
}
.setup-item {
padding: 9px 10px;
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
}
.setup-item span {
display: block;
color: var(--muted);
font-size: 9px;
}
.setup-item strong {
display: block;
margin-top: 3px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
.card {
position: relative;
overflow: hidden;
margin-bottom: 14px;
padding: 16px;
border: 1px solid var(--border);
border-radius: 15px;
background:
linear-gradient(145deg, rgba(255, 255, 255, 0.025), transparent 70%),
var(--panel-2);
}
.card::before {
position: absolute;
top: 0;
right: 0;
left: 0;
height: 2px;
background: var(--accent);
content: "";
}
.card.elastic {
--accent: var(--green);
}
.card.inelastic {
--accent: var(--orange);
}
.card-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
margin-bottom: 13px;
}
.card h2 {
margin: 0;
font-size: 15px;
}
.card .kind {
margin-top: 4px;
color: var(--muted);
font-size: 10px;
}
.e-badge {
flex: 0 0 auto;
padding: 6px 8px;
border: 1px solid color-mix(in srgb, var(--accent) 38%, transparent);
border-radius: 8px;
background: color-mix(in srgb, var(--accent) 10%, transparent);
color: var(--accent);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
font-weight: 800;
}
.ledger {
display: grid;
gap: 7px;
margin-bottom: 12px;
}
.ledger-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
padding-bottom: 7px;
border-bottom: 1px solid rgba(164, 190, 226, 0.08);
color: var(--muted);
font-size: 10px;
}
.ledger-row strong {
color: #e8f0fc;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
font-weight: 650;
}
.dot {
display: inline-block;
width: 6px;
height: 6px;
margin-right: 6px;
border-radius: 50%;
}
.dot.cyan {
background: var(--cyan);
box-shadow: 0 0 7px rgba(73, 184, 255, 0.55);
}
.dot.pink {
background: var(--pink);
box-shadow: 0 0 7px rgba(255, 107, 139, 0.55);
}
.primary-metric {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-bottom: 10px;
}
.metric-box {
padding: 10px;
border: 1px solid rgba(164, 190, 226, 0.1);
border-radius: 10px;
background: rgba(5, 10, 20, 0.25);
}
.metric-box span {
display: block;
color: var(--muted);
font-size: 9px;
}
.metric-box strong {
display: block;
margin-top: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 14px;
}
.metric-box.good strong {
color: var(--green);
}
.metric-box.loss strong {
color: var(--orange);
}
.energy-track {
position: relative;
height: 7px;
overflow: hidden;
margin: 7px 0 13px;
border-radius: 999px;
background: #202b3f;
}
.energy-fill {
display: block;
width: 100%;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--accent), color-mix(in srgb, var(--accent) 55%, white));
transition: width 80ms linear;
}
.energy-caption {
display: flex;
justify-content: space-between;
color: var(--muted);
font-size: 9px;
}
.result-note {
min-height: 34px;
margin: 0;
padding: 9px 10px;
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
color: #afbed2;
font-size: 10px;
line-height: 1.45;
}
.principle {
padding: 15px;
border: 1px solid rgba(169, 139, 255, 0.2);
border-radius: 14px;
background: rgba(169, 139, 255, 0.06);
}
.principle h3 {
margin: 0 0 8px;
color: #d7cbff;
font-size: 12px;
}
.principle p {
margin: 6px 0 0;
color: #aebbd0;
font-size: 10px;
line-height: 1.55;
}
.principle strong {
color: #e4dcff;
}
@media (max-width: 900px) {
body {
overflow: auto;
}
#app {
flex-direction: column;
height: auto;
}
#stage {
min-height: 570px;
height: 68dvh;
}
#panel {
width: 100%;
flex-basis: auto;
overflow: visible;
border-top: 1px solid var(--border);
border-left: 0;
}
.hero {
top: 18px;
left: 18px;
right: 18px;
}
.subtitle {
max-width: 560px;
}
.transport {
right: 14px;
bottom: 14px;
left: 14px;
}
.view-hint {
right: 16px;
bottom: 110px;
}
}
@media (max-width: 520px) {
.transport-top {
flex-wrap: wrap;
}
.time-readout {
width: 100%;
margin-left: 0;
}
.primary-metric {
grid-template-columns: 1fr;
}
.hero h1 {
font-size: 29px;
}
}
</style>
</head>
<body>
<main id="app">
<section id="stage" aria-label="Interactive 3D collision comparison">
<header class="hero">
<div class="eyebrow">Matched collision experiment</div>
<h1>Momentum is conserved.<br />Kinetic energy is not.</h1>
<p class="subtitle">
The same masses and initial velocities are used in both tracks.
The elastic collision exchanges energy through deformation, while the
perfectly inelastic collision sticks together and loses kinetic energy.
</p>
<div class="phase">
<span></span>
<b id="phaseText">Approaching collision</b>
</div>
</header>
<div class="view-hint">Drag to orbit · Wheel to zoom · Double-click to reset view</div>
<div class="transport">
<div class="transport-top">
<button class="control-button primary" id="playButton" type="button">Pause</button>
<button class="control-button" id="replayButton" type="button">Replay</button>
<button class="control-button" id="cameraButton" type="button">Reset camera</button>
<label class="time-readout" for="speedSelect">
t = <span id="timeText">0.000</span> s
</label>
<label class="time-readout" for="speedSelect">
Speed
<select
id="speedSelect"
style="
margin-left: 5px;
border: 1px solid #30405b;
border-radius: 6px;
background: #111a2b;
color: #dce8f8;
padding: 4px 6px;
"
>
<option value="0.5">0.5×</option>
<option value="1" selected>1×</option>
<option value="1.5">1.5×</option>
</select>
</label>
</div>
<div class="timeline-wrap">
<input
id="timeline"
type="range"
min="0"
max="3.2"
step="0.001"
value="0"
aria-label="Collision timeline"
/>
<div class="impact-marker"></div>
<div class="impact-label">Impact</div>
</div>
</div>
</section>
<aside id="panel">
<h2 class="panel-title">Experiment controls</h2>
<p class="panel-copy">
No external horizontal force acts on either pair, so total linear
momentum is conserved in both collisions.
</p>
<div class="setup">
<div class="setup-heading">Identical initial conditions</div>
<div class="setup-grid">
<div class="setup-item">
<span>Body 1</span>
<strong>m₁ = 2 kg</strong>
</div>
<div class="setup-item">
<span>Body 2</span>
<strong>m₂ = 1 kg</strong>
</div>
<div class="setup-item">
<span>Initial velocities</span>
<strong>u₁ = +3, u₂ = −1 m/s</strong>
</div>
<div class="setup-item">
<span>Initial momentum</span>
<strong>P₀ = +5 kg·m/s</strong>
</div>
<div class="setup-item">
<span>Initial kinetic energy</span>
<strong>K₀ = 9.50 J</strong>
</div>
<div class="setup-item">
<span>Impact time</span>
<strong>t = 1.20 s</strong>
</div>
</div>
</div>
<section class="card elastic">
<div class="card-head">
<div>
<h2>Elastic collision</h2>
<div class="kind">Relative separation speed is preserved</div>
</div>
<div class="e-badge">e = 1.00</div>
</div>
<div class="ledger">
<div class="ledger-row">
<span><i class="dot cyan"></i>Individual momentum p₁</span>
<strong id="eP1">+6.00</strong>
</div>
<div class="ledger-row">
<span><i class="dot pink"></i>Individual momentum p₂</span>
<strong id="eP2">−1.00</strong>
</div>
</div>
<div class="primary-metric">
<div class="metric-box">
<span>Total momentum P</span>
<strong id="eTotalP">+5.00</strong>
</div>
<div class="metric-box good">
<span>Total momentum change ΔP</span>
<strong id="eDeltaP">0.00</strong>
</div>
</div>
<div class="ledger">
<div class="ledger-row">
<span>Current kinetic energy K</span>
<strong><span id="eK">9.50</span> J</strong>
</div>
<div class="ledger-row">
<span>Kinetic-energy change ΔK</span>
<strong><span id="eDeltaK">0.00</span> J</strong>
</div>
</div>
<div class="energy-track">
<span class="energy-fill" id="eEnergyFill"></span>
</div>
<div class="energy-caption">
<span>Remaining kinetic energy</span>
<span id="eLoss">Loss: 0.00 J</span>
</div>
<p class="result-note">
Momentum and kinetic energy are both conserved. The bodies exchange
velocities without sticking together.
</p>
</section>
<section class="card inelastic">
<div class="card-head">
<div>
<h2>Perfectly inelastic</h2>
<div class="kind">Bodies stick and share one velocity</div>
</div>
<div class="e-badge">e = 0.00</div>
</div>
<div class="ledger">
<div class="ledger-row">
<span><i class="dot cyan"></i>Individual momentum p₁</span>
<strong id="iP1">+6.00</strong>
</div>
<div class="ledger-row">
<span><i class="dot pink"></i>Individual momentum p₂</span>
<strong id="iP2">−1.00</strong>
</div>
</div>
<div class="primary-metric">
<div class="metric-box">
<span>Total momentum P</span>
<strong id="iTotalP">+5.00</strong>
</div>
<div class="metric-box good">
<span>Total momentum change ΔP</span>
<strong id="iDeltaP">0.00</strong>
</div>
</div>
<div class="ledger">
<div class="ledger-row">
<span>Current kinetic energy K</span>
<strong><span id="iK">9.50</span> J</strong>
</div>
<div class="ledger-row">
<span>Kinetic-energy change ΔK</span>
<strong><span id="iDeltaK">0.00</span> J</strong>
</div>
</div>
<div class="energy-track">
<span class="energy-fill" id="iEnergyFill"></span>
</div>
<div class="energy-caption">
<span>Remaining kinetic energy</span>
<span id="iLoss">Loss: 0.00 J</span>
</div>
<p class="result-note">
Total momentum still does not change. However, 5.33 J of kinetic
energy is lost to deformation, heat, and sound after the bodies stick.
</p>
</section>
<div class="principle">
<h3>Momentum change ≠ kinetic-energy loss</h3>
<p>
In both cases, <strong>ΔP_total = 0</strong>. Individual momenta change
because the collision forces redistribute momentum between the bodies.
</p>
<p>
For <strong>e = 1</strong>, the deformation energy is returned, so
<strong>ΔK = 0</strong>. For <strong>e = 0</strong>, some mechanical
energy is permanently dissipated, so <strong>ΔK < 0</strong> even
though total momentum remains constant.
</p>
</div>
</aside>
</main>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Physical model
// -------------------------------------------------------------------------
const physics = {
m1: 2,
m2: 1,
u1: 3,
u2: -1,
x1: -3,
x2: 3,
bodyLength: 1.2,
collisionTime: 1.2,
duration: 3.2
};
physics.P0 = physics.m1 * physics.u1 + physics.m2 * physics.u2;
physics.K0 =
0.5 * physics.m1 * physics.u1 * physics.u1 +
0.5 * physics.m2 * physics.u2 * physics.u2;
// For a one-dimensional collision:
// v1 = [m1u1 + m2u2 - m2e(u1-u2)] / (m1+m2)
// v2 = [m1u1 + m2u2 + m1e(u1-u2)] / (m1+m2)
function finalVelocities(e) {
const numerator1 =
physics.m1 * physics.u1 +
physics.m2 * physics.u2 -
physics.m2 * e * (physics.u1 - physics.u2);
const numerator2 =
physics.m1 * physics.u1 +
physics.m2 * physics.u2 +
physics.m1 * e * (physics.u1 - physics.u2);
return {
v1: numerator1 / (physics.m1 + physics.m2),
v2: numerator2 / (physics.m1 + physics.m2)
};
}
const elasticFinal = finalVelocities(1);
const inelasticFinal = finalVelocities(0);
const contactX1 =
physics.x1 + physics.u1 * physics.collisionTime;
const contactX2 =
physics.x2 + physics.u2 * physics.collisionTime;
const contactCenter = (contactX1 + contactX2) / 2;
function sampleCollision(isElastic, time) {
let x1;
let x2;
let v1;
let v2;
if (time <= physics.collisionTime) {
x1 = physics.x1 + physics.u1 * time;
x2 = physics.x2 + physics.u2 * time;
v1 = physics.u1;
v2 = physics.u2;
} else if (isElastic) {
const elapsed = time - physics.collisionTime;
x1 = contactX1 + elasticFinal.v1 * elapsed;
x2 = contactX2 + elasticFinal.v2 * elapsed;
v1 = elasticFinal.v1;
v2 = elasticFinal.v2;
} else {
const elapsed = time - physics.collisionTime;
const commonVelocity = inelasticFinal.v1;
const groupCenter = contactCenter + commonVelocity * elapsed;
x1 = groupCenter - physics.bodyLength / 2;
x2 = groupCenter + physics.bodyLength / 2;
v1 = commonVelocity;
v2 = commonVelocity;
}
const p1 = physics.m1 * v1;
const p2 = physics.m2 * v2;
const totalP = p1 + p2;
const kineticEnergy =
0.5 * physics.m1 * v1 * v1 +
0.5 * physics.m2 * v2 * v2;
return { x1, x2, v1, v2, p1, p2, totalP, kineticEnergy };
}
// -------------------------------------------------------------------------
// DOM and renderer
// -------------------------------------------------------------------------
const $ = (selector) => document.querySelector(selector);
const stage = $("#stage");
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
stage.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b14);
scene.fog = new THREE.Fog(0x070b14, 17, 36);
const camera = new THREE.PerspectiveCamera(40, 1, 0.1, 100);
const cameraState = {
yaw: 0,
pitch: 0.49,
radius: 19,
touched: false
};
const cameraTarget = new THREE.Vector3(0, 0.35, 0);
function idealCameraRadius() {
const aspect = stage.clientWidth / Math.max(stage.clientHeight, 1);
return aspect < 1 ? 34 : aspect < 1.35 ? 25 : 19;
}
function updateCamera() {
const r = cameraState.radius;
const horizontalRadius = Math.cos(cameraState.pitch) * r;
camera.position.set(
cameraTarget.x + Math.sin(cameraState.yaw) * horizontalRadius,
cameraTarget.y + Math.sin(cameraState.pitch) * r,
cameraTarget.z + Math.cos(cameraState.yaw) * horizontalRadius
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraState.yaw = 0;
cameraState.pitch = 0.49;
cameraState.radius = idealCameraRadius();
cameraState.touched = false;
updateCamera();
}
cameraState.radius = idealCameraRadius();
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xa8ceff, 0x11101b, 1.8);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(-5, 10, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -14;
keyLight.shadow.camera.right = 14;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x668dff, 1.6);
rimLight.position.set(8, 5, -9);
scene.add(rimLight);
const cyanLight = new THREE.PointLight(0x49b8ff, 18, 12, 2);
cyanLight.position.set(-5, 2.5, 4.5);
scene.add(cyanLight);
const pinkLight = new THREE.PointLight(0xff6b8b, 15, 12, 2);
pinkLight.position.set(5, 2.3, -3.2);
scene.add(pinkLight);
// -------------------------------------------------------------------------
// Helpers and environment
// -------------------------------------------------------------------------
function roundedRect(context, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + r, y);
context.arcTo(x + width, y, x + width, y + height, r);
context.arcTo(x + width, y + height, x, y + height, r);
context.arcTo(x, y + height, x, y, r);
context.arcTo(x, y, x + width, y, r);
context.closePath();
}
function makeLabelSprite(
text,
worldWidth,
worldHeight,
options = {}
) {
const canvas = document.createElement("canvas");
canvas.width = 1024;
canvas.height = 256;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(
context,
8,
8,
canvas.width - 16,
canvas.height - 16,
34
);
context.fillStyle = options.background || "rgba(9, 16, 29, 0.86)";
context.fill();
context.strokeStyle = options.border || "rgba(167, 195, 230, 0.24)";
context.lineWidth = 4;
context.stroke();
if (options.accent) {
roundedRect(context, 24, 36, 10, 184, 5);
context.fillStyle = options.accent;
context.fill();
}
context.fillStyle = options.color || "#e9f2ff";
context.font =
options.font ||
"700 60px system-ui, -apple-system, BlinkMacSystemFont, Segoe UI, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, canvas.width / 2 + 14, canvas.height / 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(worldWidth, worldHeight, 1);
sprite.renderOrder = 10;
return sprite;
}
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(42, 28),
new THREE.MeshStandardMaterial({
color: 0x080d18,
roughness: 0.94,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.42;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(38, 19, 0x29415f, 0x152238);
grid.position.y = -0.39;
grid.material.transparent = true;
grid.material.opacity = 0.27;
scene.add(grid);
// Small background stars add depth without distracting from the tracks.
const starPositions = [];
let seed = 91;
function seededRandom() {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
}
for (let i = 0; i < 140; i++) {
starPositions.push(
(seededRandom() - 0.5) * 35,
seededRandom() * 13 + 1,
(seededRandom() - 0.5) * 24
);
}
const starGeometry = new THREE.BufferGeometry();
starGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(starPositions, 3)
);
const stars = new THREE.Points(
starGeometry,
new THREE.PointsMaterial({
color: 0x7da4d5,
size: 0.035,
transparent: true,
opacity: 0.42,
depthWrite: false
})
);
scene.add(stars);
const laneZ = {
elastic: 2.55,
inelastic: -2.55
};
function createTrack(z, accent, label, subtitle) {
const group = new THREE.Group();
const platform = new THREE.Mesh(
new THREE.BoxGeometry(25, 0.18, 2.2),
new THREE.MeshStandardMaterial({
color: 0x101a2b,
roughness: 0.58,
metalness: 0.42
})
);
platform.position.set(0, 0, z);
platform.receiveShadow = true;
group.add(platform);
for (const side of [-1, 1]) {
const rail = new THREE.Mesh(
new THREE.BoxGeometry(25, 0.075, 0.055),
new THREE.MeshStandardMaterial({
color: accent,
emissive: accent,
emissiveIntensity: 0.7,
roughness: 0.38
})
);
rail.position.set(0, 0.14, z + side * 1.04);
group.add(rail);
}
const dashMaterial = new THREE.MeshStandardMaterial({
color: 0x60738f,
emissive: 0x283a55,
emissiveIntensity: 0.35,
roughness: 0.7
});
for (let x = -11.5; x <= 11.5; x += 1.05) {
const dash = new THREE.Mesh(
new THREE.BoxGeometry(0.38, 0.025, 0.045),
dashMaterial
);
dash.position.set(x, 0.105, z);
group.add(dash);
}
const laneLabel = makeLabelSprite(
`${label} • ${subtitle}`,
4.7,
0.95,
{
accent: accent === 0x58e1ad ? "#58e1ad" : "#ffb45b",
border:
accent === 0x58e1ad
? "rgba(88,225,173,0.35)"
: "rgba(255,180,91,0.35)",
font: "750 55px system-ui, sans-serif"
}
);
laneLabel.position.set(-8.45, 0.66, z);
group.add(laneLabel);
return group;
}
scene.add(
createTrack(
laneZ.elastic,
0x58e1ad,
"e = 1.00",
"ELASTIC"
)
);
scene.add(
createTrack(
laneZ.inelastic,
0xffb45b,
"e = 0.00",
"PERFECTLY INELASTIC"
)
);
// -------------------------------------------------------------------------
// Carts, labels, momentum arrows, and impact effects
// -------------------------------------------------------------------------
const wheelGeometry = new THREE.CylinderGeometry(
0.19,
0.19,
0.13,
20
);
wheelGeometry.rotateX(Math.PI / 2);
const bodyGeometry = new THREE.BoxGeometry(
physics.bodyLength,
0.64,
0.9
);
const topGeometry = new THREE.BoxGeometry(0.95, 0.09, 0.76);
const wheelMaterial = new THREE.MeshStandardMaterial({
color: 0x111827,
roughness: 0.46,
metalness: 0.66
});
function createCart(mass, color, z) {
const group = new THREE.Group();
const body = new THREE.Mesh(
bodyGeometry,
new THREE.MeshStandardMaterial({
color,
roughness: 0.38,
metalness: 0.32,
emissive: color,
emissiveIntensity: 0.08
})
);
body.position.y = 0.67;
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const top = new THREE.Mesh(
topGeometry,
new THREE.MeshStandardMaterial({
color: 0xe9f4ff,
roughness: 0.32,
metalness: 0.25
})
);
top.position.set(-0.04, 1.02, 0);
top.castShadow = true;
group.add(top);
for (const x of [-0.36, 0.36]) {
for (const wheelZ of [-0.47, 0.47]) {
const wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
wheel.position.set(x, 0.27, wheelZ);
wheel.castShadow = true;
group.add(wheel);
}
}
const badge = makeLabelSprite(
`${mass} kg`,
0.82,
0.29,
{
background: "rgba(5, 11, 21, 0.82)",
border: "rgba(225, 239, 255, 0.28)",
color: "#f0f7ff",
font: "800 82px system-ui, sans-serif"
}
);
badge.position.set(0, 0.67, 0.49);
group.add(badge);
group.position.z = z;
scene.add(group);
const arrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
1,
color,
0.28,
0.16
);
arrow.line.material.transparent = true;
arrow.line.material.opacity = 0.88;
arrow.cone.material.transparent = true;
arrow.cone.material.opacity = 0.95;
scene.add(arrow);
return { group, arrow };
}
const elasticCart1 = createCart(2, 0x49b8ff, laneZ.elastic);
const elasticCart2 = createCart(1, 0xff6b8b, laneZ.elastic);
const inelasticCart1 = createCart(2, 0x49b8ff, laneZ.inelastic);
const inelasticCart2 = createCart(1, 0xff6b8b, laneZ.inelastic);
// Glowing seam makes the stuck-together state explicit.
const stuckSeam = new THREE.Mesh(
new THREE.BoxGeometry(0.09, 0.16, 0.96),
new THREE.MeshStandardMaterial({
color: 0xffcf82,
emissive: 0xff9f32,
emissiveIntensity: 2.1,
roughness: 0.3
})
);
stuckSeam.visible = false;
scene.add(stuckSeam);
function createImpactEffect(z, color) {
const ringMaterial = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0,
depthWrite: false
});
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.26, 0.035, 10, 48),
ringMaterial
);
ring.rotation.x = Math.PI / 2;
ring.position.set(contactCenter, 0.18, z);
ring.visible = false;
scene.add(ring);
const sparkMaterial = new THREE.MeshBasicMaterial({ color });
const sparks = [];
for (let i = 0; i < 16; i++) {
const spark = new THREE.Mesh(
new THREE.SphereGeometry(0.045, 7, 7),
sparkMaterial
);
spark.visible = false;
scene.add(spark);
sparks.push(spark);
}
return { ring, sparks };
}
const elasticImpact = createImpactEffect(laneZ.elastic, 0x58e1ad);
const inelasticImpact = createImpactEffect(laneZ.inelastic, 0xffb45b);
function updateImpact(effect, time) {
const elapsed = time - physics.collisionTime;
if (elapsed < 0 || elapsed > 0.72) {
effect.ring.visible = false;
effect.sparks.forEach((spark) => {
spark.visible = false;
});
return;
}
effect.ring.visible = true;
effect.ring.scale.setScalar(1 + elapsed * 4.3);
effect.ring.material.opacity = Math.max(0, 1 - elapsed / 0.72);
effect.sparks.forEach((spark, index) => {
const angle = (index / effect.sparks.length) * Math.PI * 2;
const speed = 1.8 + (index % 5) * 0.25;
spark.visible = true;
spark.position.set(
contactCenter + Math.cos(angle) * speed * elapsed,
Math.max(0.17, 0.32 + 2.4 * elapsed - 4.5 * elapsed * elapsed),
effect.ring.position.z + Math.sin(angle) * speed * 0.72 * elapsed
);
spark.scale.setScalar(Math.max(0.05, 1 - elapsed / 0.72));
});
}
function updateArrow(arrow, momentum, x, z) {
const magnitude = Math.abs(momentum);
const direction = momentum >= 0 ? 1 : -1;
arrow.position.set(x, 1.48, z);
arrow.setDirection(new THREE.Vector3(direction, 0, 0));
arrow.setLength(Math.max(0.06, magnitude * 0.48), 0.28, 0.16);
arrow.visible = magnitude > 0.01;
}
// -------------------------------------------------------------------------
// Animation and UI
// -------------------------------------------------------------------------
let simulationTime = 0;
let playing = true;
let playbackSpeed = 1;
const playButton = $("#playButton");
const replayButton = $("#replayButton");
const cameraButton = $("#cameraButton");
const timeline = $("#timeline");
const speedSelect = $("#speedSelect");
function signed(value, digits = 2) {
const safeValue = Math.abs(value) < 0.0000001 ? 0 : value;
return `${safeValue >= 0 ? "+" : "−"}${Math.abs(safeValue).toFixed(digits)}`;
}
function plain(value, digits = 2) {
const safeValue = Math.abs(value) < 0.0000001 ? 0 : value;
return `${safeValue.toFixed(digits)}`;
}
function updateReadouts(isElastic, prefix) {
const state = sampleCollision(isElastic, simulationTime);
const loss = Math.max(0, physics.K0 - state.kineticEnergy);
$(`${prefix}P1`).textContent = signed(state.p1);
$(`${prefix}P2`).textContent = signed(state.p2);
$(`${prefix}TotalP`).textContent = signed(state.totalP);
$(`${prefix}DeltaP`).textContent = signed(
state.totalP - physics.P0
);
$(`${prefix}K`).textContent = plain(state.kineticEnergy);
$(`${prefix}DeltaK`).textContent = signed(
state.kineticEnergy - physics.K0
);
$(`${prefix}Loss`).textContent = `Loss: ${plain(loss)} J`;
const percentage = Math.max(
0,
Math.min(100, (state.kineticEnergy / physics.K0) * 100)
);
$(`${prefix}EnergyFill`).style.width = `${percentage}%`;
}
function updateScene() {
const elastic = sampleCollision(true, simulationTime);
const inelastic = sampleCollision(false, simulationTime);
elasticCart1.group.position.x = elastic.x1;
elasticCart2.group.position.x = elastic.x2;
inelasticCart1.group.position.x = inelastic.x1;
inelasticCart2.group.position.x = inelastic.x2;
updateArrow(
elasticCart1.arrow,
elastic.p1,
elastic.x1,
laneZ.elastic
);
updateArrow(
elasticCart2.arrow,
elastic.p2,
elastic.x2,
laneZ.elastic
);
updateArrow(
inelasticCart1.arrow,
inelastic.p1,
inelastic.x1,
laneZ.inelastic
);
updateArrow(
inelasticCart2.arrow,
inelastic.p2,
inelastic.x2,
laneZ.inelastic
);
const hasCollided = simulationTime > physics.collisionTime + 0.01;
stuckSeam.visible = hasCollided;
stuckSeam.position.set(
(inelastic.x1 + inelastic.x2) / 2,
0.55,
laneZ.inelastic
);
updateImpact(elasticImpact, simulationTime);
updateImpact(inelasticImpact, simulationTime);
updateReadouts(true, "#e");
updateReadouts(false, "#i");
timeline.value = simulationTime.toFixed(3);
const progress = (simulationTime / physics.duration) * 100;
timeline.style.setProperty("--progress", `${progress}%`);
$("#timeText").textContent = simulationTime.toFixed(3);
let phase;
if (simulationTime < physics.collisionTime - 0.025) {
phase = "Approaching collision";
} else if (simulationTime <= physics.collisionTime + 0.035) {
phase = "Impact";
} else {
phase = "Post-collision comparison";
}
$("#phaseText").textContent = phase;
}
// The phase wording is neutral while the shared impact is active.
const originalPhaseUpdate = updateScene;
playButton.addEventListener("click", () => {
if (simulationTime >= physics.duration - 0.001) {
simulationTime = 0;
}
playing = !playing;
playButton.textContent = playing ? "Pause" : "Play";
});
replayButton.addEventListener("click", () => {
simulationTime = 0;
playing = true;
playButton.textContent = "Pause";
});
cameraButton.addEventListener("click", resetCamera);
timeline.addEventListener("input", () => {
simulationTime = Number(timeline.value);
playing = false;
playButton.textContent = "Play";
});
speedSelect.addEventListener("change", () => {
playbackSpeed = Number(speedSelect.value);
});
// -------------------------------------------------------------------------
// Custom camera controls — no addons are imported.
// -------------------------------------------------------------------------
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
cameraState.touched = true;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.004,
0.22,
1.12
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
});
function endDrag(event) {
dragging = false;
if (
event.pointerId !== undefined &&
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.touched = true;
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.012,
10,
42
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = Math.max(stage.clientWidth, 1);
const height = Math.max(stage.clientHeight, 1);
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
if (!cameraState.touched) {
cameraState.radius = idealCameraRadius();
updateCamera();
}
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(stage);
resize();
let previousTime = performance.now();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (playing) {
simulationTime += delta * playbackSpeed;
if (simulationTime >= physics.duration) {
simulationTime = physics.duration;
playing = false;
playButton.textContent = "Play";
}
}
originalPhaseUpdate();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```