Prompt specification
Build or customize the Three.js 3D scene "Like and unlike charge 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: Like and unlike charge comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/like-and-unlike-charge-comparison-x1610
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts electrostatic forces between charges. Show matched pairs of equal-magnitude charges with identical separation; display repulsion for like signs and attraction for opposite signs without moving charges through each other. Stylized solid forms.
Working Three.js Starter (like-and-unlike-charge-comparison-x1610):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Electrostatic Force Comparison</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 23, 40, 0.82);
--border: rgba(170, 210, 255, 0.16);
--text: #eef7ff;
--muted: #91a8bf;
--positive: #ff727d;
--negative: #58ddff;
--force: #ffd166;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 2;
}
.header {
position: absolute;
top: 24px;
left: 28px;
max-width: 520px;
}
.eyebrow {
margin-bottom: 8px;
color: var(--force);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.22em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(25px, 3.1vw, 42px);
line-height: 1;
letter-spacing: -0.045em;
}
.subtitle {
max-width: 470px;
margin: 12px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.constants {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 15px;
}
.constant {
padding: 7px 10px;
border: 1px solid var(--border);
border-radius: 999px;
background: rgba(10, 23, 40, 0.65);
color: #c8d9e9;
font-size: 11px;
letter-spacing: 0.04em;
}
.controls {
position: absolute;
top: 24px;
right: 26px;
display: flex;
gap: 8px;
pointer-events: auto;
}
button {
appearance: none;
border: 1px solid var(--border);
border-radius: 10px;
padding: 10px 13px;
background: rgba(13, 28, 47, 0.88);
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 650;
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
button:hover {
background: rgba(25, 48, 74, 0.95);
border-color: rgba(180, 220, 255, 0.35);
transform: translateY(-1px);
}
button:focus-visible {
outline: 2px solid var(--force);
outline-offset: 3px;
}
.panel {
border: 1px solid var(--border);
background: var(--panel);
box-shadow: 0 16px 45px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(14px);
}
.legend {
position: absolute;
left: 26px;
bottom: 26px;
width: 288px;
padding: 15px 16px;
border-radius: 14px;
}
.legend-title {
margin-bottom: 11px;
color: #d9e8f7;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
margin: 8px 0;
color: #b8cadc;
font-size: 12px;
}
.swatch {
width: 12px;
height: 12px;
flex: 0 0 auto;
border-radius: 50%;
box-shadow: 0 0 0 4px rgba(255, 255, 255, 0.035);
}
.swatch.positive {
background: var(--positive);
}
.swatch.negative {
background: var(--negative);
}
.swatch.force {
width: 23px;
height: 3px;
border-radius: 2px;
background: var(--force);
box-shadow: none;
}
.guard {
margin-top: 12px;
padding-top: 11px;
border-top: 1px solid var(--border);
color: #8098ae;
font-size: 10px;
line-height: 1.5;
}
.metrics {
position: absolute;
right: 26px;
bottom: 26px;
width: 306px;
padding: 15px 16px;
border-radius: 14px;
}
.metrics-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
}
.metrics-title {
font-size: 11px;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
#sim-state {
color: #72efb0;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
}
.metric {
display: grid;
grid-template-columns: 38px 1fr 54px;
align-items: center;
gap: 9px;
min-height: 28px;
border-top: 1px solid rgba(170, 210, 255, 0.08);
font-size: 11px;
}
.metric:first-of-type {
border-top: 0;
}
.metric-signs {
font-size: 17px;
font-weight: 850;
letter-spacing: -0.08em;
}
.metric-label {
color: #9db2c7;
}
.metric-value {
color: #dce9f5;
text-align: right;
font-variant-numeric: tabular-nums;
}
.hint {
position: absolute;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
color: rgba(181, 205, 227, 0.52);
font-size: 10px;
letter-spacing: 0.08em;
white-space: nowrap;
}
#loading {
position: fixed;
inset: 0;
z-index: 5;
display: grid;
place-items: center;
background: var(--bg);
color: var(--muted);
font-size: 12px;
letter-spacing: 0.14em;
text-transform: uppercase;
transition: opacity 300ms ease;
}
#loading.hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 980px) {
.metrics {
display: none;
}
.hint {
left: auto;
right: 24px;
transform: none;
}
}
@media (max-width: 680px) {
.header {
top: 18px;
left: 18px;
right: 18px;
}
.subtitle {
display: none;
}
.controls {
top: auto;
right: 16px;
bottom: 16px;
}
button {
padding: 9px 10px;
font-size: 11px;
}
.legend {
left: 16px;
bottom: 70px;
width: 240px;
padding: 12px;
}
.guard,
.hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D electrostatic force comparison"></canvas>
<div class="hud">
<header class="header">
<div class="eyebrow">Electrostatic comparison</div>
<h1>Charge. Motion. Force.</h1>
<p class="subtitle">
Four matched pairs share the same charge magnitude and starting
separation. Like charges push apart; opposite charges pull together
without ever passing through one another.
</p>
<div class="constants">
<div class="constant">|q| = 1.00 q₀ per charge</div>
<div class="constant">Initial gap = 2.20 units</div>
<div class="constant">Protective center gap = 0.94 units</div>
</div>
</header>
<div class="controls">
<button id="toggle" type="button">Pause motion</button>
<button id="reset" type="button">Reset</button>
<button id="reset-view" type="button">Reset view</button>
</div>
<aside class="legend panel">
<div class="legend-title">Visual key</div>
<div class="legend-row">
<span class="swatch positive"></span>
<span>Positive charge</span>
</div>
<div class="legend-row">
<span class="swatch negative"></span>
<span>Negative charge</span>
</div>
<div class="legend-row">
<span class="swatch force"></span>
<span>Direction of electrostatic force</span>
</div>
<div class="guard">
The attractive pairs use a hard center-distance constraint. Their
surfaces stop before contact, so the charges can never cross or
occupy the same position.
</div>
</aside>
<aside class="metrics panel">
<div class="metrics-header">
<div class="metrics-title">Live pair gaps</div>
<div id="sim-state">LIVE</div>
</div>
<div class="metric">
<div class="metric-signs" style="color: var(--positive)">++</div>
<div class="metric-label">Repulsion</div>
<div class="metric-value" id="gap-0">2.20</div>
</div>
<div class="metric">
<div class="metric-signs" style="color: var(--negative)">−−</div>
<div class="metric-label">Repulsion</div>
<div class="metric-value" id="gap-1">2.20</div>
</div>
<div class="metric">
<div class="metric-signs" style="color: var(--negative)">+−</div>
<div class="metric-label">Attraction</div>
<div class="metric-value" id="gap-2">2.20</div>
</div>
<div class="metric">
<div class="metric-signs" style="color: var(--positive)">−+</div>
<div class="metric-label">Attraction</div>
<div class="metric-value" id="gap-3">2.20</div>
</div>
</aside>
<div class="hint">Drag to orbit · Scroll to zoom · Space to pause</div>
</div>
<div id="loading">Loading electrostatic scene…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Scene setup
// ---------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const loading = document.querySelector("#loading");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 21, 52);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.75, 0);
const spherical = new THREE.Spherical(15.5, 1.15, 0);
const hemisphere = new THREE.HemisphereLight(0xb9ddff, 0x07101d, 1.65);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(6, 12, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -14;
keyLight.shadow.camera.right = 14;
keyLight.shadow.camera.top = 12;
keyLight.shadow.camera.bottom = -12;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.00035;
scene.add(keyLight);
const positiveLight = new THREE.PointLight(0xff5966, 24, 22, 2);
positiveLight.position.set(-8, 5, 5);
scene.add(positiveLight);
const negativeLight = new THREE.PointLight(0x35cfff, 24, 22, 2);
negativeLight.position.set(8, 5, -5);
scene.add(negativeLight);
const ground = new THREE.Mesh(
new THREE.CircleGeometry(30, 96),
new THREE.MeshStandardMaterial({
color: 0x081522,
roughness: 0.94,
metalness: 0.02
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.13;
ground.receiveShadow = true;
scene.add(ground);
// ---------------------------------------------------------------------
// Simulation constants
// ---------------------------------------------------------------------
const INITIAL_GAP = 2.2;
const CHARGE_RADIUS = 0.43;
// Hard center-distance limit prevents attraction from passing charges
// through each other.
const MIN_CENTER_GAP = CHARGE_RADIUS * 2 + 0.08;
const MAX_CENTER_GAP = 3.25;
const COULOMB = 1.15;
const FORCE_COLOR = 0xffd166;
const POSITIVE_COLOR = 0xff727d;
const NEGATIVE_COLOR = 0x58ddff;
const AXIS_Y = new THREE.Vector3(0, 1, 0);
const forceDirection = new THREE.Vector3();
const pairDefinitions = [
{
qLeft: 1,
qRight: 1,
title: "POSITIVE + POSITIVE",
relation: "REPULSION · PUSHING APART",
accent: 0xffd166,
position: [-4.25, 0, -2.35]
},
{
qLeft: -1,
qRight: -1,
title: "NEGATIVE − NEGATIVE",
relation: "REPULSION · PUSHING APART",
accent: 0xffd166,
position: [4.25, 0, -2.35]
},
{
qLeft: 1,
qRight: -1,
title: "POSITIVE + NEGATIVE",
relation: "ATTRACTION · PULLING TOGETHER",
accent: 0x58ddff,
position: [-4.25, 0, 2.35]
},
{
qLeft: -1,
qRight: 1,
title: "NEGATIVE − POSITIVE",
relation: "ATTRACTION · PULLING TOGETHER",
accent: 0x58ddff,
position: [4.25, 0, 2.35]
}
];
const pairs = [];
// ---------------------------------------------------------------------
// Canvas-based labels and charge symbols
// ---------------------------------------------------------------------
function roundedRectPath(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 createPairLabel(title, relation, accent) {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 768;
labelCanvas.height = 224;
const ctx = labelCanvas.getContext("2d");
const accentCss = `#${accent.toString(16).padStart(6, "0")}`;
roundedRectPath(ctx, 8, 8, 752, 208, 30);
ctx.fillStyle = "rgba(8, 20, 35, 0.94)";
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = accentCss;
ctx.globalAlpha = 0.82;
ctx.stroke();
ctx.globalAlpha = 1;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#eef7ff";
ctx.font = "800 39px system-ui, sans-serif";
ctx.fillText(title, 384, 78);
ctx.fillStyle = accentCss;
ctx.font = "750 27px system-ui, sans-serif";
ctx.fillText(relation, 384, 143);
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
toneMapped: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(3.85, 1.12, 1);
sprite.position.set(0, 2.73, 0);
sprite.renderOrder = 3;
return sprite;
}
const signTextures = new Map();
function getSignTexture(sign) {
if (signTextures.has(sign)) {
return signTextures.get(sign);
}
const symbolCanvas = document.createElement("canvas");
symbolCanvas.width = 256;
symbolCanvas.height = 256;
const ctx = symbolCanvas.getContext("2d");
ctx.beginPath();
ctx.arc(128, 128, 106, 0, Math.PI * 2);
ctx.fillStyle = "rgba(5, 14, 27, 0.72)";
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = "rgba(255, 255, 255, 0.22)";
ctx.stroke();
ctx.fillStyle = "#ffffff";
ctx.font = "800 154px Arial, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(sign > 0 ? "+" : "−", 128, 132);
const texture = new THREE.CanvasTexture(symbolCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
signTextures.set(sign, texture);
return texture;
}
// ---------------------------------------------------------------------
// Solid scene objects
// ---------------------------------------------------------------------
function createCharge(sign, parent) {
const group = new THREE.Group();
group.position.y = 0.78;
const color = sign > 0 ? POSITIVE_COLOR : NEGATIVE_COLOR;
const emissive = sign > 0 ? 0x5e1019 : 0x07384f;
const sphere = new THREE.Mesh(
new THREE.SphereGeometry(CHARGE_RADIUS, 48, 32),
new THREE.MeshStandardMaterial({
color,
emissive,
emissiveIntensity: 0.28,
roughness: 0.3,
metalness: 0.08
})
);
sphere.castShadow = true;
sphere.receiveShadow = true;
group.add(sphere);
const badge = new THREE.Mesh(
new THREE.PlaneGeometry(0.56, 0.56),
new THREE.MeshBasicMaterial({
map: getSignTexture(sign),
transparent: true,
depthWrite: false,
toneMapped: false
})
);
badge.renderOrder = 4;
group.add(badge);
parent.add(group);
return { group, sphere, badge };
}
function createForceArrow() {
const group = new THREE.Group();
const material = new THREE.MeshStandardMaterial({
color: FORCE_COLOR,
emissive: 0x5b3900,
emissiveIntensity: 0.42,
roughness: 0.35,
metalness: 0.12
});
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(0.045, 0.045, 1, 16),
material
);
const head = new THREE.Mesh(
new THREE.ConeGeometry(0.13, 0.27, 20),
material
);
group.add(shaft, head);
group.userData.shaft = shaft;
group.userData.head = head;
return group;
}
function setArrowLength(arrow, length, directionX) {
const headLength = 0.27;
const shaftLength = Math.max(0.06, length - headLength);
arrow.userData.shaft.scale.y = shaftLength;
arrow.userData.shaft.position.y = shaftLength / 2;
arrow.userData.head.position.y = shaftLength + headLength / 2;
forceDirection.set(directionX, 0, 0);
arrow.quaternion.setFromUnitVectors(AXIS_Y, forceDirection);
}
function createPair(definition, index) {
const group = new THREE.Group();
group.position.set(...definition.position);
scene.add(group);
const platform = new THREE.Mesh(
new THREE.CylinderGeometry(2.35, 2.48, 0.22, 64),
new THREE.MeshStandardMaterial({
color: 0x111f31,
roughness: 0.78,
metalness: 0.08
})
);
platform.castShadow = true;
platform.receiveShadow = true;
group.add(platform);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(2.02, 0.027, 10, 96),
new THREE.MeshStandardMaterial({
color: definition.accent,
emissive: definition.accent,
emissiveIntensity: 0.12,
roughness: 0.4,
metalness: 0.22
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.13;
group.add(ring);
const rail = new THREE.Mesh(
new THREE.BoxGeometry(INITIAL_GAP, 0.035, 0.12),
new THREE.MeshStandardMaterial({
color: 0x36506b,
roughness: 0.58,
metalness: 0.2
})
);
rail.position.y = 0.18;
group.add(rail);
const tickGeometry = new THREE.BoxGeometry(0.035, 0.085, 0.19);
const tickMaterial = new THREE.MeshStandardMaterial({
color: 0x6d8aa4,
roughness: 0.5
});
const leftTick = new THREE.Mesh(tickGeometry, tickMaterial);
const rightTick = new THREE.Mesh(tickGeometry, tickMaterial);
leftTick.position.y = 0.19;
rightTick.position.y = 0.19;
group.add(leftTick, rightTick);
const label = createPairLabel(
definition.title,
definition.relation,
definition.accent
);
group.add(label);
const left = createCharge(definition.qLeft, group);
const right = createCharge(definition.qRight, group);
const leftArrow = createForceArrow();
const rightArrow = createForceArrow();
group.add(leftArrow, rightArrow);
const pair = {
index,
definition,
group,
rail,
leftTick,
rightTick,
left,
right,
leftArrow,
rightArrow,
velocityLeft: 0,
velocityRight: 0,
gap: INITIAL_GAP
};
resetPair(pair);
pairs.push(pair);
}
pairDefinitions.forEach(createPair);
// ---------------------------------------------------------------------
// Physics
// ---------------------------------------------------------------------
function resetPair(pair) {
pair.left.group.position.x = -INITIAL_GAP / 2;
pair.right.group.position.x = INITIAL_GAP / 2;
pair.velocityLeft = 0;
pair.velocityRight = 0;
pair.gap = INITIAL_GAP;
}
function simulatePair(pair, dt) {
const qLeft = pair.definition.qLeft;
const qRight = pair.definition.qRight;
let gap = pair.right.group.position.x - pair.left.group.position.x;
gap = Math.max(gap, MIN_CENTER_GAP);
const center =
(pair.left.group.position.x + pair.right.group.position.x) / 2;
// Signed Coulomb force. A positive product repels; a negative product
// attracts. Equal and opposite forces preserve each pair's center.
const signedForce = (COULOMB * qLeft * qRight) / (gap * gap);
pair.velocityLeft += -signedForce * dt;
pair.velocityRight += signedForce * dt;
const damping = Math.exp(-0.75 * dt);
pair.velocityLeft *= damping;
pair.velocityRight *= damping;
pair.left.group.position.x += pair.velocityLeft * dt;
pair.right.group.position.x += pair.velocityRight * dt;
let newGap =
pair.right.group.position.x - pair.left.group.position.x;
// Hard collision/ordering constraint. Charges cannot cross, even if
// the attractive acceleration is very strong at a short distance.
if (newGap < MIN_CENTER_GAP) {
pair.left.group.position.x = center - MIN_CENTER_GAP / 2;
pair.right.group.position.x = center + MIN_CENTER_GAP / 2;
if (qLeft * qRight < 0) {
pair.velocityLeft = 0;
pair.velocityRight = 0;
} else {
pair.velocityLeft = -Math.abs(pair.velocityLeft);
pair.velocityRight = Math.abs(pair.velocityRight);
}
newGap = MIN_CENTER_GAP;
}
// Keep the comparison compact while preserving the repulsion.
if (newGap > MAX_CENTER_GAP) {
pair.left.group.position.x = center - MAX_CENTER_GAP / 2;
pair.right.group.position.x = center + MAX_CENTER_GAP / 2;
if (qLeft * qRight > 0) {
pair.velocityLeft = 0;
pair.velocityRight = 0;
}
newGap = MAX_CENTER_GAP;
}
pair.gap = newGap;
pair.rail.scale.x = newGap / INITIAL_GAP;
pair.leftTick.position.x = pair.left.group.position.x;
pair.rightTick.position.x = pair.right.group.position.x;
const forceMagnitude =
(COULOMB * Math.abs(qLeft * qRight)) / (newGap * newGap);
const initialForce = COULOMB / (INITIAL_GAP * INITIAL_GAP);
const forceRatio = forceMagnitude / initialForce;
const arrowLength = THREE.MathUtils.clamp(
0.5 + 0.3 * Math.sqrt(forceRatio),
0.5,
1.05
);
const likeCharges = qLeft === qRight;
// Like charges: both force arrows point away from the other charge.
// Opposite charges: both force arrows point toward the other charge.
const leftDirection = likeCharges ? -1 : 1;
const rightDirection = likeCharges ? 1 : -1;
pair.leftArrow.position.set(
pair.left.group.position.x,
1.49,
-0.04
);
pair.rightArrow.position.set(
pair.right.group.position.x,
1.82,
0.04
);
setArrowLength(pair.leftArrow, arrowLength, leftDirection);
setArrowLength(pair.rightArrow, arrowLength, rightDirection);
}
// ---------------------------------------------------------------------
// Camera controls implemented directly without add-ons
// ---------------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
function updateCamera() {
camera.position.setFromSpherical(spherical).add(cameraTarget);
camera.lookAt(cameraTarget);
}
function resetView() {
const aspect = window.innerWidth / window.innerHeight;
spherical.theta = 0;
spherical.phi = aspect < 0.75 ? 0.87 : 1.15;
spherical.radius =
aspect < 0.75 ? 29 : aspect < 1.2 ? 20.5 : 15.5;
updateCamera();
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
spherical.theta -= dx * 0.006;
spherical.phi -= dy * 0.006;
spherical.phi = THREE.MathUtils.clamp(spherical.phi, 0.35, 1.48);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (
event.pointerId !== undefined &&
canvas.hasPointerCapture(event.pointerId)
) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
spherical.radius *= Math.exp(event.deltaY * 0.001);
spherical.radius = THREE.MathUtils.clamp(
spherical.radius,
9,
34
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetView);
// ---------------------------------------------------------------------
// UI controls
// ---------------------------------------------------------------------
const toggleButton = document.querySelector("#toggle");
const simState = document.querySelector("#sim-state");
let running = true;
function setRunning(value) {
running = value;
toggleButton.textContent = running ? "Pause motion" : "Resume motion";
simState.textContent = running ? "LIVE" : "PAUSED";
simState.style.color = running ? "#72efb0" : "#ffd166";
}
toggleButton.addEventListener("click", () => {
setRunning(!running);
});
document.querySelector("#reset").addEventListener("click", () => {
pairs.forEach(resetPair);
setRunning(true);
});
document.querySelector("#reset-view").addEventListener("click", resetView);
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
setRunning(!running);
}
if (event.key.toLowerCase() === "r") {
pairs.forEach(resetPair);
setRunning(true);
}
});
// ---------------------------------------------------------------------
// Animation and resizing
// ---------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
const chargeWorldPosition = new THREE.Vector3();
const cameraDirection = new THREE.Vector3();
const clock = new THREE.Clock();
let frame = 0;
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.033);
if (running) {
pairs.forEach((pair) => simulatePair(pair, dt));
}
// Keep the embossed symbols facing the camera as the view changes.
pairs.forEach((pair) => {
for (const charge of [pair.left, pair.right]) {
charge.group.getWorldPosition(chargeWorldPosition);
cameraDirection
.copy(camera.position)
.sub(chargeWorldPosition)
.normalize();
charge.badge.position
.copy(cameraDirection)
.multiplyScalar(CHARGE_RADIUS * 1.025);
charge.badge.lookAt(camera.position);
}
});
if (frame % 4 === 0) {
pairs.forEach((pair) => {
const output = document.querySelector(`#gap-${pair.index}`);
if (output) {
output.textContent = pair.gap.toFixed(2);
}
});
}
renderer.render(scene, camera);
frame += 1;
}
resetView();
resize();
animate();
requestAnimationFrame(() => {
loading.classList.add("hidden");
setTimeout(() => loading.remove(), 350);
});
</script>
</body>
</html>
```