Prompt specification
Build or customize the Three.js 3D scene "Same position different velocity demonstrations" 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: Same position different velocity demonstrations
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/same-position-different-velocity-demonstrations-x1406
Scene Description Prompt:
Make a stylized Three.js scene in a self-contained HTML file using cdnjs: the same position different velocity demonstrations. Show two carts passing the same marker simultaneously with different velocities; highlight equal instantaneous position while retaining distinct slopes on their position-time graphs.
Working Three.js Starter (same-position-different-velocity-demonstrations-x1406):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Same Position — Different Velocity</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(9, 20, 35, 0.78);
--line: rgba(155, 202, 235, 0.16);
--text: #eef8ff;
--muted: #8fa9bf;
--cyan: #4de3ff;
--coral: #ff6b5f;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.overlay {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
border: 1px solid var(--line);
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.title-panel {
position: absolute;
top: 24px;
left: 24px;
width: min(390px, calc(100vw - 48px));
padding: 22px 24px 20px;
border-radius: 18px;
}
.eyebrow {
margin-bottom: 10px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.19em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(28px, 3.2vw, 43px);
line-height: 0.98;
letter-spacing: -0.045em;
}
h1 span {
color: var(--cyan);
}
.description {
margin: 15px 0 18px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 9px;
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 999px;
color: #d8e9f5;
font-size: 11px;
font-weight: 700;
}
.dot {
width: 8px;
height: 8px;
border-radius: 50%;
box-shadow: 0 0 12px currentColor;
}
.dot.cyan {
color: var(--cyan);
background: var(--cyan);
}
.dot.coral {
color: var(--coral);
background: var(--coral);
}
.readout {
position: absolute;
top: 24px;
right: 24px;
width: 260px;
padding: 18px;
border-radius: 16px;
transition:
border-color 180ms ease,
box-shadow 180ms ease;
}
.readout.crossing {
border-color: rgba(77, 227, 255, 0.72);
box-shadow:
0 18px 60px rgba(0, 0, 0, 0.25),
0 0 30px rgba(77, 227, 255, 0.14);
}
.readout-label {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
#phase {
margin-top: 6px;
color: var(--text);
font-size: 14px;
font-weight: 800;
}
#phase-detail {
min-height: 18px;
margin-top: 3px;
color: var(--muted);
font-size: 11px;
}
.readout-grid {
display: grid;
grid-template-columns: 1fr auto;
gap: 8px 16px;
margin-top: 15px;
padding-top: 13px;
border-top: 1px solid var(--line);
font-size: 11px;
}
.readout-grid span:nth-child(odd) {
color: var(--muted);
}
.readout-grid span:nth-child(even) {
color: var(--text);
font-variant-numeric: tabular-nums;
font-weight: 700;
}
.transport {
position: absolute;
right: 24px;
bottom: 24px;
left: 24px;
display: flex;
align-items: center;
gap: 15px;
padding: 13px 15px;
border-radius: 16px;
pointer-events: auto;
}
.buttons {
display: flex;
flex-wrap: wrap;
gap: 8px;
}
button {
min-height: 36px;
padding: 0 13px;
border: 1px solid rgba(152, 199, 231, 0.2);
border-radius: 10px;
background: rgba(23, 42, 62, 0.82);
color: var(--text);
font: inherit;
font-size: 11px;
font-weight: 750;
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
button:hover {
background: rgba(37, 67, 92, 0.95);
border-color: rgba(77, 227, 255, 0.5);
transform: translateY(-1px);
}
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
button.primary {
border-color: rgba(77, 227, 255, 0.5);
background: rgba(34, 122, 151, 0.34);
color: #dffaff;
}
.timeline {
position: relative;
flex: 1;
min-width: 160px;
height: 36px;
display: flex;
align-items: center;
}
#scrub {
width: 100%;
margin: 0;
accent-color: var(--cyan);
cursor: pointer;
}
.event-notch {
position: absolute;
top: 1px;
left: 40%;
width: 1px;
height: 12px;
background: white;
box-shadow: 0 0 8px var(--cyan);
pointer-events: none;
}
.event-caption {
position: absolute;
top: 18px;
left: 40%;
transform: translateX(-50%);
color: var(--cyan);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
white-space: nowrap;
pointer-events: none;
}
.timecode {
min-width: 92px;
color: var(--muted);
font-size: 11px;
font-variant-numeric: tabular-nums;
text-align: right;
}
.hint {
position: absolute;
bottom: 95px;
left: 28px;
color: rgba(190, 215, 232, 0.5);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
@media (max-width: 820px) {
.title-panel {
top: 14px;
left: 14px;
width: min(340px, calc(100vw - 28px));
padding: 17px 18px;
}
.description {
display: none;
}
.readout {
top: auto;
right: 14px;
bottom: 112px;
width: 218px;
}
.transport {
right: 14px;
bottom: 14px;
left: 14px;
flex-wrap: wrap;
gap: 9px;
}
.timeline {
order: 3;
flex-basis: 100%;
}
.hint {
display: none;
}
}
@media (max-width: 520px) {
h1 {
font-size: 27px;
}
.legend {
gap: 6px;
}
.legend-item {
padding: 6px 8px;
font-size: 9px;
}
.readout {
display: none;
}
.buttons button {
padding: 0 10px;
font-size: 10px;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive Three.js relative motion demonstration"></canvas>
<div class="overlay">
<header class="title-panel panel">
<div class="eyebrow">Relative Motion Laboratory</div>
<h1>Same point.<br /><span>Different velocity.</span></h1>
<p class="description">
Both carts pass the same <strong>x = 0</strong> marker at exactly the
same time. Their position–time graphs meet at one point, but the
different slopes reveal different velocities.
</p>
<div class="legend">
<div class="legend-item">
<i class="dot cyan"></i>
CART A · 1.65 m/s
</div>
<div class="legend-item">
<i class="dot coral"></i>
CART B · 0.82 m/s
</div>
</div>
</header>
<section class="readout panel" id="readout">
<div class="readout-label">Simulation state</div>
<div id="phase">Approaching marker</div>
<div id="phase-detail">Calculating crossing…</div>
<div class="readout-grid">
<span>Time</span><span id="time-value">0.00 s</span>
<span>Cart A position</span><span id="a-position">0.00 m</span>
<span>Cart B position</span><span id="b-position">0.00 m</span>
<span>Marker event</span><span>4.00 s</span>
</div>
</section>
<footer class="transport panel">
<div class="buttons">
<button class="primary" id="replay" type="button">↻ Replay</button>
<button id="jump" type="button">Crossing frame</button>
<button id="pause" type="button">Pause</button>
<button id="reset-view" type="button">Reset view</button>
</div>
<div class="timeline">
<input
id="scrub"
type="range"
min="0"
max="10"
step="0.01"
value="0"
aria-label="Simulation timeline"
/>
<i class="event-notch"></i>
<span class="event-caption">SIMULTANEOUS PASS</span>
</div>
<div class="timecode" id="timecode">t = 0.00 s</div>
</footer>
<div class="hint">Drag to orbit · Scroll or pinch to zoom</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const scrub = document.querySelector("#scrub");
const pauseButton = document.querySelector("#pause");
const readout = document.querySelector("#readout");
const phaseElement = document.querySelector("#phase");
const phaseDetail = document.querySelector("#phase-detail");
const timeElement = document.querySelector("#time-value");
const aPositionElement = document.querySelector("#a-position");
const bPositionElement = document.querySelector("#b-position");
const timecodeElement = document.querySelector("#timecode");
const COLORS = {
cyan: 0x4de3ff,
coral: 0xff6b5f,
white: 0xeef8ff,
navy: 0x07111f,
board: 0x091827,
grid: 0x31516a,
rail: 0x738a9b,
dark: 0x071019
};
const DURATION = 10;
const EVENT_TIME = 4;
const CART_A_VELOCITY = 1.65;
const CART_B_VELOCITY = 0.82;
const LANE_A = -1;
const LANE_B = 1;
let simulationTime = 0.65;
let playing = true;
// -------------------------------------------------------------------------
// Renderer and scene
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
const scene = new THREE.Scene();
scene.background = new THREE.Color(COLORS.navy);
scene.fog = new THREE.Fog(COLORS.navy, 22, 45);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const hemisphere = new THREE.HemisphereLight(0xa8dcff, 0x07101b, 2.0);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(-5, 12, 9);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -16;
keyLight.shadow.camera.right = 16;
keyLight.shadow.camera.top = 14;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 40;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4bdcff, 1.4);
rimLight.position.set(10, 7, -10);
scene.add(rimLight);
const markerLight = new THREE.PointLight(COLORS.cyan, 4, 9, 2);
markerLight.position.set(0, 2.2, 0);
scene.add(markerLight);
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
function roundedRect(ctx, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + width - r, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + r);
ctx.lineTo(x + width, y + height - r);
ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
ctx.lineTo(x + r, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
function makeLabel(text, accent = COLORS.white, width = 3.2, alwaysVisible = false) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 768;
labelCanvas.height = 160;
const ctx = labelCanvas.getContext("2d");
ctx.clearRect(0, 0, labelCanvas.width, labelCanvas.height);
roundedRect(ctx, 5, 5, 758, 150, 25);
ctx.fillStyle = "rgba(5, 14, 25, 0.91)";
ctx.fill();
ctx.lineWidth = 4;
ctx.strokeStyle = `#${new THREE.Color(accent).getHexString()}`;
ctx.stroke();
ctx.fillStyle = `#${new THREE.Color(accent).getHexString()}`;
ctx.fillRect(22, 33, 7, 94);
ctx.fillStyle = "#eef8ff";
ctx.font = "700 43px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 390, 82);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: !alwaysVisible,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width * (160 / 768), 1);
return sprite;
}
function makeBox(
width,
height,
depth,
color,
options = {}
) {
const {
roughness = 0.52,
metalness = 0.28,
emissive = 0x000000,
emissiveIntensity = 0,
outline = false,
outlineColor = 0x8db4cf
} = options;
const geometry = new THREE.BoxGeometry(width, height, depth);
const material = new THREE.MeshStandardMaterial({
color,
roughness,
metalness,
emissive,
emissiveIntensity
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
if (outline) {
const edgeGeometry = new THREE.EdgesGeometry(geometry, 22);
const edgeMaterial = new THREE.LineBasicMaterial({
color: outlineColor,
transparent: true,
opacity: 0.6
});
mesh.add(new THREE.LineSegments(edgeGeometry, edgeMaterial));
}
return mesh;
}
function addMesh(parent, mesh, x = 0, y = 0, z = 0) {
mesh.position.set(x, y, z);
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Ground and stylized railway
// -------------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(36, 23),
new THREE.MeshStandardMaterial({
color: 0x0a1928,
roughness: 0.92,
metalness: 0.08
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.set(0, -0.28, -1.2);
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(34, 34, COLORS.grid, 0x173047);
grid.position.set(0, -0.265, -1.2);
grid.material.transparent = true;
grid.material.opacity = 0.22;
scene.add(grid);
const trackBed = addMesh(
scene,
makeBox(21, 0.08, 4.7, 0x0d2233, {
roughness: 0.88,
metalness: 0.12,
outline: true,
outlineColor: 0x28485e
}),
0,
-0.16,
0
);
trackBed.receiveShadow = true;
for (let i = 0; i < 32; i += 1) {
const sleeper = makeBox(0.17, 0.10, 4.2, 0x263a49, {
roughness: 0.88,
metalness: 0.12
});
addMesh(scene, sleeper, -10.15 + i * 0.655, -0.075, 0);
}
for (const lane of [LANE_A, LANE_B]) {
for (const offset of [-0.48, 0.48]) {
const rail = makeBox(20.5, 0.14, 0.09, COLORS.rail, {
roughness: 0.3,
metalness: 0.78
});
addMesh(scene, rail, 0, 0.07, lane + offset);
}
}
for (let i = 0; i < 21; i += 1) {
const laneDash = addMesh(
scene,
makeBox(0.46, 0.025, 0.035, 0x315c73, {
emissive: 0x163a4c,
emissiveIntensity: 0.5
}),
-10 + i,
-0.08,
0
);
laneDash.castShadow = false;
}
// -------------------------------------------------------------------------
// The single shared marker: a gantry, ring, ribbon, and illuminated floor line
// -------------------------------------------------------------------------
const markerGroup = new THREE.Group();
scene.add(markerGroup);
const markerPlaneMaterial = new THREE.MeshBasicMaterial({
color: COLORS.cyan,
transparent: true,
opacity: 0.055,
side: THREE.DoubleSide,
depthWrite: false
});
const markerPlane = new THREE.Mesh(
new THREE.PlaneGeometry(5.2, 3.8),
markerPlaneMaterial
);
markerPlane.rotation.y = Math.PI / 2;
markerPlane.position.set(0, 1.8, 0);
markerGroup.add(markerPlane);
for (const z of [-2.55, 2.55]) {
addMesh(
markerGroup,
makeBox(0.18, 4.05, 0.18, 0x37566a, {
metalness: 0.68,
roughness: 0.3,
outline: true
}),
0,
1.94,
z
);
addMesh(
markerGroup,
makeBox(0.42, 0.12, 0.42, COLORS.cyan, {
emissive: COLORS.cyan,
emissiveIntensity: 1.8
}),
0,
0.04,
z
);
}
addMesh(
markerGroup,
makeBox(0.18, 0.18, 5.3, 0x37566a, {
metalness: 0.68,
roughness: 0.3,
outline: true
}),
0,
3.92,
0
);
const markerRingMaterial = new THREE.MeshBasicMaterial({
color: COLORS.cyan,
transparent: true,
opacity: 0.75
});
const markerRing = new THREE.Mesh(
new THREE.TorusGeometry(2.45, 0.045, 10, 80),
markerRingMaterial
);
markerRing.rotation.y = Math.PI / 2;
markerRing.position.set(0, 2.0, 0);
markerGroup.add(markerRing);
const floorMarkerMaterial = new THREE.MeshBasicMaterial({
color: COLORS.cyan,
transparent: true,
opacity: 0.72
});
const floorMarker = addMesh(
markerGroup,
new THREE.Mesh(new THREE.BoxGeometry(0.075, 0.035, 5.15), floorMarkerMaterial),
0,
0.015,
0
);
floorMarker.castShadow = false;
const equalPositionBeamMaterial = new THREE.MeshBasicMaterial({
color: COLORS.white,
transparent: true,
opacity: 0.4
});
const equalPositionBeam = addMesh(
markerGroup,
new THREE.Mesh(
new THREE.BoxGeometry(0.055, 0.055, 4.8),
equalPositionBeamMaterial
),
0,
0.98,
0
);
equalPositionBeam.castShadow = false;
const markerLabel = makeLabel(
"x = 0 · SAME MARKER",
COLORS.cyan,
3.5,
true
);
markerLabel.position.set(0, 4.55, 0);
markerGroup.add(markerLabel);
// -------------------------------------------------------------------------
// Carts
// -------------------------------------------------------------------------
function createCart(color, name, velocity) {
const group = new THREE.Group();
const chassis = makeBox(1.78, 0.18, 1.12, 0x152532, {
roughness: 0.42,
metalness: 0.58,
outline: true
});
addMesh(group, chassis, 0, 0.35, 0);
const body = makeBox(1.55, 0.47, 0.96, color, {
roughness: 0.38,
metalness: 0.24,
emissive: color,
emissiveIntensity: 0.08,
outline: true,
outlineColor: 0xd6f7ff
});
addMesh(group, body, 0, 0.68, 0);
const cabin = makeBox(0.78, 0.34, 0.75, 0x142938, {
roughness: 0.26,
metalness: 0.45,
outline: true,
outlineColor: color
});
addMesh(group, cabin, -0.16, 1.07, 0);
const windshield = makeBox(0.34, 0.18, 0.78, 0x71c8e9, {
roughness: 0.18,
metalness: 0.62,
emissive: 0x153c4e,
emissiveIntensity: 0.7
});
addMesh(group, windshield, 0.25, 1.09, 0);
const bumperFront = makeBox(0.12, 0.16, 1.05, 0xb8d8e7, {
roughness: 0.3,
metalness: 0.78
});
addMesh(group, bumperFront, 0.84, 0.43, 0);
const bumperBack = makeBox(0.12, 0.16, 1.05, 0xb8d8e7, {
roughness: 0.3,
metalness: 0.78
});
addMesh(group, bumperBack, -0.84, 0.43, 0);
const wheelGeometry = new THREE.CylinderGeometry(0.23, 0.23, 0.16, 18);
const wheelMaterial = new THREE.MeshStandardMaterial({
color: 0x081018,
roughness: 0.72,
metalness: 0.36
});
const hubGeometry = new THREE.CylinderGeometry(0.09, 0.09, 0.18, 14);
const hubMaterial = new THREE.MeshStandardMaterial({
color,
roughness: 0.28,
metalness: 0.72,
emissive: color,
emissiveIntensity: 0.16
});
const wheels = [];
for (const x of [-0.54, 0.54]) {
for (const z of [-0.57, 0.57]) {
const wheel = new THREE.Mesh(wheelGeometry, wheelMaterial);
wheel.rotation.x = Math.PI / 2;
wheel.position.set(x, 0.23, z);
wheel.castShadow = true;
group.add(wheel);
wheels.push(wheel);
const hub = new THREE.Mesh(hubGeometry, hubMaterial);
hub.rotation.x = Math.PI / 2;
hub.position.copy(wheel.position);
group.add(hub);
}
}
const haloMaterial = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0.22,
depthWrite: false
});
const halo = new THREE.Mesh(
new THREE.TorusGeometry(0.69, 0.025, 8, 42),
haloMaterial
);
halo.rotation.x = Math.PI / 2;
halo.position.y = 0.01;
group.add(halo);
const label = makeLabel(
`${name} · ${velocity.toFixed(2)} m/s`,
color,
3.1,
true
);
label.position.set(0, 2.05, 0);
group.add(label);
const arrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(),
velocity * 1.48,
color,
0.42,
0.25
);
scene.add(arrow);
scene.add(group);
return {
group,
wheels,
arrow,
velocity,
color
};
}
const cartA = createCart(COLORS.cyan, "CART A", CART_A_VELOCITY);
cartA.group.position.z = LANE_A;
const cartB = createCart(COLORS.coral, "CART B", CART_B_VELOCITY);
cartB.group.position.z = LANE_B;
// -------------------------------------------------------------------------
// Holographic position–time graph board
// -------------------------------------------------------------------------
const graphGroup = new THREE.Group();
graphGroup.position.set(1.65, 3.8, -6.2);
scene.add(graphGroup);
const graphFrame = makeBox(10.85, 5.65, 0.22, COLORS.board, {
roughness: 0.55,
metalness: 0.38,
outline: true,
outlineColor: 0x426a84
});
graphGroup.add(graphFrame);
const graphSurface = new THREE.Mesh(
new THREE.PlaneGeometry(10.45, 5.22),
new THREE.MeshBasicMaterial({
color: 0x071522,
transparent: true,
opacity: 0.94
})
);
graphSurface.position.z = 0.12;
graphGroup.add(graphSurface);
const graphGridMaterial = new THREE.LineBasicMaterial({
color: COLORS.grid,
transparent: true,
opacity: 0.38
});
const graphGridPoints = [];
for (let x = -4.5; x <= 4.5; x += 0.75) {
graphGridPoints.push(
new THREE.Vector3(x, -2.05, 0.17),
new THREE.Vector3(x, 2.05, 0.17)
);
}
for (let y = -2; y <= 2; y += 0.5) {
graphGridPoints.push(
new THREE.Vector3(-4.5, y, 0.17),
new THREE.Vector3(4.5, y, 0.17)
);
}
const graphGrid = new THREE.LineSegments(
new THREE.BufferGeometry().setFromPoints(graphGridPoints),
graphGridMaterial
);
graphGroup.add(graphGrid);
function updateSegment(mesh, x1, y1, x2, y2, thickness = 0.035) {
const dx = x2 - x1;
const dy = y2 - y1;
const length = Math.hypot(dx, dy);
mesh.visible = length > 0.0001;
mesh.position.set((x1 + x2) / 2, (y1 + y2) / 2, 0.225);
mesh.rotation.z = Math.atan2(dy, dx);
mesh.scale.set(length, thickness, 0.035);
}
const segmentGeometry = new THREE.BoxGeometry(1, 1, 1);
function graphSegment(color, opacity = 1) {
const mesh = new THREE.Mesh(
segmentGeometry,
new THREE.MeshBasicMaterial({
color,
transparent: opacity < 1,
opacity
})
);
graphGroup.add(mesh);
return mesh;
}
const horizontalAxis = graphSegment(0x7192a8, 0.72);
updateSegment(horizontalAxis, -4.5, 0, 4.5, 0, 0.025);
const verticalAxis = graphSegment(0x7192a8, 0.72);
updateSegment(verticalAxis, 0, -2.05, 0, 2.05, 0.025);
const eventAxisMaterial = new THREE.MeshBasicMaterial({
color: 0xe8fbff,
transparent: true,
opacity: 0.68
});
const eventAxis = new THREE.Mesh(
new THREE.BoxGeometry(0.025, 4.15, 0.035),
eventAxisMaterial
);
eventAxis.position.set(0, 0, 0.215);
graphGroup.add(eventAxis);
const graphSlopeA = 0.42;
const graphSlopeB = 0.21;
const fullLineA = graphSegment(COLORS.cyan);
updateSegment(fullLineA, -4.4, graphSlopeA * -4.4, 4.4, graphSlopeA * 4.4, 0.055);
const fullLineB = graphSegment(COLORS.coral);
updateSegment(fullLineB, -4.4, graphSlopeB * -4.4, 4.4, graphSlopeB * 4.4, 0.055);
const traceA = graphSegment(0xb8f5ff);
const traceB = graphSegment(0xffb3aa);
const graphDotMaterialA = new THREE.MeshBasicMaterial({ color: 0xd7fbff });
const graphDotMaterialB = new THREE.MeshBasicMaterial({ color: 0xffd0ca });
const graphDotA = new THREE.Mesh(
new THREE.SphereGeometry(0.085, 16, 12),
graphDotMaterialA
);
const graphDotB = new THREE.Mesh(
new THREE.SphereGeometry(0.085, 16, 12),
graphDotMaterialB
);
graphGroup.add(graphDotA, graphDotB);
const graphCursor = new THREE.Mesh(
new THREE.BoxGeometry(0.022, 4.1, 0.025),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.42
})
);
graphCursor.position.z = 0.205;
graphGroup.add(graphCursor);
const graphEventDot = new THREE.Mesh(
new THREE.SphereGeometry(0.11, 20, 14),
new THREE.MeshBasicMaterial({ color: 0xffffff })
);
graphEventDot.position.set(0, 0, 0.31);
graphGroup.add(graphEventDot);
const graphPulseMaterial = new THREE.MeshBasicMaterial({
color: COLORS.cyan,
transparent: true,
opacity: 0.75,
depthWrite: false
});
const graphPulse = new THREE.Mesh(
new THREE.TorusGeometry(0.22, 0.025, 8, 48),
graphPulseMaterial
);
graphPulse.position.set(0, 0, 0.29);
graphGroup.add(graphPulse);
const graphTitle = makeLabel(
"POSITION–TIME · SLOPE = VELOCITY",
0xa9d7ec,
5.35,
false
);
graphTitle.position.set(0, 2.43, 0.34);
graphGroup.add(graphTitle);
const graphLegendA = makeLabel(
"FAST · Δx/Δt = 1.65 m/s",
COLORS.cyan,
3.45,
false
);
graphLegendA.position.set(-2.45, 1.75, 0.35);
graphGroup.add(graphLegendA);
const graphLegendB = makeLabel(
"SLOW · Δx/Δt = 0.82 m/s",
COLORS.coral,
3.45,
false
);
graphLegendB.position.set(-2.45, 1.29, 0.35);
graphGroup.add(graphLegendB);
const graphSamePoint = makeLabel(
"SAME POSITION",
0xffffff,
2.25,
false
);
graphSamePoint.position.set(0.65, 0.34, 0.38);
graphGroup.add(graphSamePoint);
const graphAxisTime = makeLabel("TIME", 0x8fb0c7, 1.25, false);
graphAxisTime.position.set(4.1, -0.36, 0.35);
graphGroup.add(graphAxisTime);
const graphAxisPosition = makeLabel("POSITION", 0x8fb0c7, 1.65, false);
graphAxisPosition.position.set(-3.75, 2.04, 0.35);
graphGroup.add(graphAxisPosition);
// -------------------------------------------------------------------------
// Custom camera controls: orbit, wheel zoom, touch orbit and pinch zoom
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 1.15, -1.0);
const defaultView = {
theta: 0.64,
phi: 1.05,
radius: 21
};
const desiredCamera = { ...defaultView };
const currentCamera = { ...defaultView };
function updateCamera(delta) {
const damping = 1 - Math.pow(0.001, delta);
currentCamera.theta +=
(desiredCamera.theta - currentCamera.theta) * damping;
currentCamera.phi +=
(desiredCamera.phi - currentCamera.phi) * damping;
currentCamera.radius +=
(desiredCamera.radius - currentCamera.radius) * damping;
const sinPhi = Math.sin(currentCamera.phi);
camera.position.set(
cameraTarget.x +
currentCamera.radius *
sinPhi *
Math.sin(currentCamera.theta),
cameraTarget.y + currentCamera.radius * Math.cos(currentCamera.phi),
cameraTarget.z +
currentCamera.radius *
sinPhi *
Math.cos(currentCamera.theta)
);
camera.lookAt(cameraTarget);
}
const pointers = new Map();
let lastPointerX = 0;
let lastPointerY = 0;
let previousPinchDistance = 0;
canvas.addEventListener("pointerdown", (event) => {
canvas.setPointerCapture(event.pointerId);
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 1) {
lastPointerX = event.clientX;
lastPointerY = event.clientY;
} else if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
previousPinchDistance = Math.hypot(a.x - b.x, a.y - b.y);
}
});
canvas.addEventListener("pointermove", (event) => {
if (!pointers.has(event.pointerId)) return;
pointers.set(event.pointerId, {
x: event.clientX,
y: event.clientY
});
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
const distance = Math.hypot(a.x - b.x, a.y - b.y);
if (previousPinchDistance > 0 && distance > 0) {
desiredCamera.radius *=
previousPinchDistance / distance;
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius,
11,
32
);
}
previousPinchDistance = distance;
} else {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
desiredCamera.theta -= dx * 0.006;
desiredCamera.phi = THREE.MathUtils.clamp(
desiredCamera.phi - dy * 0.005,
0.48,
1.38
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
}
});
function removePointer(event) {
pointers.delete(event.pointerId);
previousPinchDistance = 0;
if (pointers.size === 1) {
const remaining = [...pointers.values()][0];
lastPointerX = remaining.x;
lastPointerY = remaining.y;
}
}
canvas.addEventListener("pointerup", removePointer);
canvas.addEventListener("pointercancel", removePointer);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
desiredCamera.radius *= Math.exp(event.deltaY * 0.001);
desiredCamera.radius = THREE.MathUtils.clamp(
desiredCamera.radius,
11,
32
);
},
{ passive: false }
);
// -------------------------------------------------------------------------
// UI controls
// -------------------------------------------------------------------------
function setPlaying(value) {
playing = value;
pauseButton.textContent = playing ? "Pause" : "Play";
}
document.querySelector("#replay").addEventListener("click", () => {
simulationTime = 0;
setPlaying(true);
});
document.querySelector("#jump").addEventListener("click", () => {
simulationTime = EVENT_TIME;
setPlaying(false);
});
pauseButton.addEventListener("click", () => {
setPlaying(!playing);
});
document.querySelector("#reset-view").addEventListener("click", () => {
desiredCamera.theta = defaultView.theta;
desiredCamera.phi = defaultView.phi;
desiredCamera.radius = defaultView.radius;
});
scrub.addEventListener("input", (event) => {
simulationTime = Number(event.target.value);
setPlaying(false);
});
window.addEventListener("keydown", (event) => {
if (event.target instanceof HTMLInputElement) return;
if (event.code === "Space") {
event.preventDefault();
setPlaying(!playing);
}
if (event.key.toLowerCase() === "r") {
simulationTime = 0;
setPlaying(true);
}
});
// -------------------------------------------------------------------------
// Simulation and rendering
// -------------------------------------------------------------------------
function updateCart(cart, lane, elapsedTime) {
const relativeTime = simulationTime - EVENT_TIME;
const x = relativeTime * cart.velocity;
cart.group.position.x = x;
cart.group.position.z = lane;
const wheelRotation = (x / 0.23) * 0.12;
for (const wheel of cart.wheels) {
wheel.rotation.z = -wheelRotation;
}
cart.arrow.position.set(x - 0.15, 0.34, lane);
cart.arrow.setDirection(new THREE.Vector3(1, 0, 0));
cart.group.children[cart.group.children.length - 2]?.position.set(
0,
1.78 + Math.sin(elapsedTime * 5 + lane) * 0.025,
0
);
}
function updateGraph() {
const relativeTime = simulationTime - EVENT_TIME;
const graphTime = THREE.MathUtils.clamp(relativeTime, -4.4, 4.4);
updateSegment(
traceA,
0,
0,
graphTime,
graphSlopeA * graphTime,
0.07
);
updateSegment(
traceB,
0,
0,
graphTime,
graphSlopeB * graphTime,
0.07
);
graphDotA.position.set(
graphTime,
graphSlopeA * graphTime,
0.33
);
graphDotB.position.set(
graphTime,
graphSlopeB * graphTime,
0.33
);
graphCursor.position.x = graphTime;
}
function updateReadout() {
const relativeTime = simulationTime - EVENT_TIME;
const xA = relativeTime * CART_A_VELOCITY;
const xB = relativeTime * CART_B_VELOCITY;
const atCrossing = Math.abs(relativeTime) < 0.065;
readout.classList.toggle("crossing", atCrossing);
if (atCrossing) {
phaseElement.textContent = "SIMULTANEOUS CROSSING";
phaseDetail.textContent = "Both carts are at x = 0.00 m";
} else if (relativeTime < 0) {
phaseElement.textContent = "Approaching marker";
phaseDetail.textContent = `${Math.abs(relativeTime).toFixed(2)} s until both pass`;
} else {
phaseElement.textContent = "Past marker";
phaseDetail.textContent = "The faster cart is pulling ahead";
}
timeElement.textContent = `${simulationTime.toFixed(2)} s`;
aPositionElement.textContent = `${xA.toFixed(2)} m`;
bPositionElement.textContent = `${xB.toFixed(2)} m`;
timecodeElement.textContent = `t = ${simulationTime.toFixed(2)} s`;
if (document.activeElement !== scrub) {
scrub.value = simulationTime.toFixed(2);
}
}
function updateScene(elapsedTime) {
const relativeTime = simulationTime - EVENT_TIME;
const crossingPulse = Math.exp(
-Math.pow(relativeTime / 0.16, 2)
);
const ambientPulse = 0.5 + 0.5 * Math.sin(elapsedTime * 2.4);
updateCart(cartA, LANE_A, elapsedTime);
updateCart(cartB, LANE_B, elapsedTime);
updateGraph();
updateReadout();
markerPlaneMaterial.opacity = 0.045 + crossingPulse * 0.14;
markerRingMaterial.opacity =
0.42 + ambientPulse * 0.12 + crossingPulse * 0.4;
floorMarkerMaterial.opacity =
0.5 + ambientPulse * 0.15 + crossingPulse * 0.35;
equalPositionBeamMaterial.opacity =
0.25 + crossingPulse * 0.72;
markerRing.scale.setScalar(1 + crossingPulse * 0.07);
markerLight.intensity = 3 + ambientPulse * 1.2 + crossingPulse * 19;
graphPulseMaterial.opacity = 0.36 + crossingPulse * 0.62;
graphPulse.scale.setScalar(1 + crossingPulse * 1.25);
graphEventDot.scale.setScalar(1 + crossingPulse * 0.75);
}
function onResize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
}
window.addEventListener("resize", onResize);
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = Math.min(clock.getDelta(), 0.05);
const elapsedTime = clock.elapsedTime;
if (playing) {
simulationTime += delta;
if (simulationTime >= DURATION) {
simulationTime %= DURATION;
}
}
updateScene(elapsedTime);
updateCamera(delta);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```