Prompt specification
Build or customize the Three.js 3D scene "Approaching magnet and induced loop arrows" 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: Approaching magnet and induced loop arrows
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/approaching-magnet-and-induced-loop-arrows-x1641
Scene Description Prompt:
Approaching magnet and induced loop arrows. Build a magnet moving toward a loop with symbolic induced-current and field arrows; show the induced field opposing the increasing external flux under a stated orientation convention. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (approaching-magnet-and-induced-loop-arrows-x1641):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Induced Current in a Loop</title>
<style>
:root {
color-scheme: dark;
--panel: rgba(8, 18, 32, 0.82);
--border: rgba(164, 211, 255, 0.18);
--text: #eaf4ff;
--muted: #9db2c9;
--gold: #ffc857;
--cyan: #2be7ff;
--violet: #b58cff;
--green: #62f5b5;
--orange: #ffad66;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #07111f;
color: var(--text);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
canvas:active {
cursor: grabbing;
}
.hud {
position: fixed;
inset: 0;
z-index: 10;
pointer-events: none;
}
.panel {
position: absolute;
padding: 16px 18px;
border: 1px solid var(--border);
border-radius: 15px;
background: var(--panel);
box-shadow: 0 14px 45px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(13px);
-webkit-backdrop-filter: blur(13px);
}
#title {
top: 20px;
left: 20px;
width: min(390px, calc(100vw - 40px));
}
#title h1 {
margin: 0 0 7px;
font-size: clamp(21px, 2.4vw, 30px);
line-height: 1.08;
letter-spacing: -0.035em;
}
#title p {
margin: 0;
color: var(--muted);
font-size: 13px;
line-height: 1.45;
}
#convention {
top: 20px;
right: 20px;
width: min(370px, calc(100vw - 40px));
font-size: 13px;
line-height: 1.5;
}
#convention h2,
#legend h2 {
margin: 0 0 10px;
font-size: 12px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: #cfe2f8;
}
.rule {
height: 1px;
margin: 10px 0;
background: var(--border);
}
.convention-list {
display: grid;
grid-template-columns: 18px 1fr;
column-gap: 8px;
row-gap: 5px;
margin: 0;
}
.convention-list .key {
color: var(--gold);
font-weight: 800;
text-align: center;
}
.convention-list .key.cyan {
color: var(--cyan);
}
.convention-list .key.violet {
color: var(--violet);
}
.convention-list .value {
color: #c5d5e7;
}
.important {
color: var(--text);
font-weight: 700;
}
#legend {
bottom: 20px;
left: 20px;
min-width: 245px;
font-size: 12px;
}
.legend-row {
display: flex;
align-items: center;
gap: 9px;
margin: 7px 0;
color: #c7d7e8;
}
.swatch {
width: 23px;
height: 4px;
border-radius: 10px;
flex: none;
}
.swatch.gold {
background: var(--gold);
box-shadow: 0 0 10px rgba(255, 200, 87, 0.7);
}
.swatch.cyan {
background: var(--cyan);
box-shadow: 0 0 10px rgba(43, 231, 255, 0.7);
}
.swatch.violet {
background: var(--violet);
box-shadow: 0 0 10px rgba(181, 140, 255, 0.7);
}
#controls {
position: absolute;
right: 20px;
bottom: 20px;
display: flex;
gap: 8px;
pointer-events: auto;
}
button {
appearance: none;
border: 1px solid rgba(180, 220, 255, 0.25);
border-radius: 10px;
padding: 10px 13px;
color: var(--text);
background: rgba(15, 31, 52, 0.92);
font: inherit;
font-size: 12px;
font-weight: 700;
cursor: pointer;
transition:
background 160ms ease,
border-color 160ms ease,
transform 160ms ease;
}
button:hover {
background: rgba(29, 53, 82, 0.98);
border-color: rgba(120, 220, 255, 0.55);
transform: translateY(-1px);
}
button:focus-visible {
outline: 2px solid var(--cyan);
outline-offset: 2px;
}
#status {
position: absolute;
left: 50%;
bottom: 22px;
transform: translateX(-50%);
display: flex;
align-items: center;
gap: 10px;
max-width: calc(100vw - 600px);
padding: 11px 16px;
border: 1px solid rgba(98, 245, 181, 0.25);
border-radius: 999px;
background: rgba(7, 25, 28, 0.9);
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.25);
color: #d8fff0;
font-size: 12px;
font-weight: 750;
white-space: nowrap;
}
#status.receding {
border-color: rgba(255, 173, 102, 0.28);
background: rgba(37, 24, 15, 0.9);
color: #ffe3c9;
}
#status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 12px var(--green);
flex: none;
}
#status.receding #status-dot {
background: var(--orange);
box-shadow: 0 0 12px var(--orange);
}
.hint {
margin-top: 8px;
color: #7890a9;
font-size: 11px;
font-weight: 500;
}
@media (max-width: 900px) {
#convention {
top: auto;
bottom: 82px;
right: 12px;
width: 315px;
font-size: 11px;
}
#title {
top: 12px;
left: 12px;
}
#legend {
display: none;
}
#status {
left: 12px;
bottom: 12px;
transform: none;
max-width: calc(100vw - 190px);
overflow: hidden;
text-overflow: ellipsis;
}
#controls {
right: 12px;
bottom: 12px;
}
button {
padding: 9px 10px;
}
}
@media (max-width: 620px) {
#convention {
display: none;
}
#status {
max-width: calc(100vw - 170px);
font-size: 10px;
}
}
</style>
</head>
<body>
<div class="hud">
<section id="title" class="panel">
<h1>Magnet → Conducting Loop</h1>
<p>
A north pole approaches a low-poly conducting loop. Watch the
induced-current arrow and the induced field reverse when the magnet
recedes.
</p>
</section>
<section id="convention" class="panel">
<h2>Orientation Convention</h2>
<div class="convention-list">
<div class="key violet">+x</div>
<div class="value">
Points from the magnet toward and through the loop.
Choose the loop normal as <span class="important">n = +x</span>.
</div>
<div class="key">B</div>
<div class="value">
The north pole faces +x, so the external field at the loop is
<span class="important">B<sub>ext</sub> = +x</span>.
</div>
<div class="key violet">↻</div>
<div class="value">
Viewed from the +x side, right-hand-rule positive current is
counterclockwise.
</div>
<div class="key cyan">Σ</div>
<div class="value">
Lenz’s law makes the induced field oppose the
<span class="important">change</span> in external flux, not the
external field itself.
</div>
</div>
<div class="rule"></div>
<div>
<span class="important">While approaching:</span>
dΦ<sub>ext</sub>/dt > 0, so B<sub>ind</sub> = −x and I<sub>ind</sub>
is <span class="important">clockwise viewed from +x</span>.
</div>
</section>
<section id="legend" class="panel">
<h2>Scene Key</h2>
<div class="legend-row">
<div class="swatch gold"></div>
<span>External magnetic field B<sub>ext</sub></span>
</div>
<div class="legend-row">
<div class="swatch cyan"></div>
<span>Induced field and induced-current direction</span>
</div>
<div class="legend-row">
<div class="swatch violet"></div>
<span>Loop normal and magnet motion</span>
</div>
</section>
<div id="status" role="status" aria-live="polite">
<span id="status-dot"></span>
<span id="status-text">
APPROACHING · dΦext/dt > 0 · Bind = −x · Iind CW from +x
</span>
</div>
<div id="controls">
<button id="pause" type="button">Pause</button>
<button id="replay" type="button">Replay</button>
<button id="reset-camera" type="button">Reset view</button>
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------------
// Renderer, scene, and camera
// ------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 12, 25);
const camera = new THREE.PerspectiveCamera(
46,
window.innerWidth / window.innerHeight,
0.1,
60
);
const cameraTarget = new THREE.Vector3(-0.45, -0.05, 0);
let cameraAzimuth = 0.76;
let cameraElevation = 0.31;
let cameraRadius = 9.6;
function updateCamera() {
const horizontalRadius = cameraRadius * Math.cos(cameraElevation);
camera.position.set(
cameraTarget.x + horizontalRadius * Math.sin(cameraAzimuth),
cameraTarget.y + cameraRadius * Math.sin(cameraElevation),
cameraTarget.z + horizontalRadius * Math.cos(cameraAzimuth)
);
camera.lookAt(cameraTarget);
}
updateCamera();
// ------------------------------------------------------------------
// Lighting and ground
// ------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xaadfff, 0x101526, 1.7));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.8);
keyLight.position.set(4, 8, 6);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 25;
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 8;
keyLight.shadow.camera.bottom = -8;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x26dfff, 7, 10, 2);
rimLight.position.set(1.7, 1.3, 2.4);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({
color: 0x0a1725,
roughness: 0.94,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -2.12;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(20, 20, 0x31516c, 0x193146);
grid.position.y = -2.105;
grid.material.transparent = true;
grid.material.opacity = 0.34;
scene.add(grid);
// ------------------------------------------------------------------
// Helpers
// ------------------------------------------------------------------
const Y_AXIS = new THREE.Vector3(0, 1, 0);
function makeLabel(text, color = "#ffffff", width = 1.6, height = 0.38) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(4, 12, 24, 0.82)";
context.fillRect(8, 10, 496, 108);
context.strokeStyle = "rgba(175, 220, 255, 0.25)";
context.lineWidth = 3;
context.strokeRect(8, 10, 496, 108);
const fontSize = text.length > 18 ? 35 : text.length > 12 ? 42 : 52;
context.font = `700 ${fontSize}px system-ui, sans-serif`;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = color;
context.fillText(text, 256, 65);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, height, 1);
sprite.renderOrder = 20;
return sprite;
}
function makeArrow(parent, start, end, color, radius = 0.035, headRadius = 0.14) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
direction.normalize();
const headLength = Math.min(headRadius * 2.25, length * 0.38);
const shaftLength = Math.max(length - headLength, 0.01);
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.58,
roughness: 0.4,
metalness: 0.12
});
const shaft = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, shaftLength, 6),
material
);
shaft.position.copy(start).addScaledVector(direction, shaftLength / 2);
shaft.quaternion.setFromUnitVectors(Y_AXIS, direction);
shaft.castShadow = true;
parent.add(shaft);
const head = new THREE.Mesh(
new THREE.ConeGeometry(headRadius, headLength, 6),
material
);
head.position.copy(end).addScaledVector(direction, -headLength / 2);
head.quaternion.setFromUnitVectors(Y_AXIS, direction);
head.castShadow = true;
parent.add(head);
return { shaft, head, material };
}
function createCurrentArrow(directionSign) {
const group = new THREE.Group();
const radius = 1.69;
const points = [];
// Looking from +x toward the loop:
// increasing theta is counterclockwise, decreasing theta is clockwise.
const startAngle = directionSign < 0 ? 2.55 : -0.65;
const endAngle = directionSign < 0 ? -0.65 : 2.55;
const pointCount = 52;
for (let i = 0; i < pointCount; i++) {
const t = i / (pointCount - 1);
const angle = THREE.MathUtils.lerp(startAngle, endAngle, t);
points.push(
new THREE.Vector3(
0.45 + 0.22,
radius * Math.cos(angle),
radius * Math.sin(angle)
)
);
}
const curve = new THREE.CatmullRomCurve3(points, false, "centripetal");
const tube = new THREE.Mesh(
new THREE.TubeGeometry(curve, 54, 0.035, 6, false),
new THREE.MeshStandardMaterial({
color: 0x2be7ff,
emissive: 0x2be7ff,
emissiveIntensity: 1.05,
roughness: 0.3,
metalness: 0.12
})
);
tube.castShadow = true;
group.add(tube);
const tangent = curve.getTangent(1).normalize();
const end = curve.getPoint(1);
const headLength = 0.3;
const head = new THREE.Mesh(
new THREE.ConeGeometry(0.145, headLength, 6),
new THREE.MeshStandardMaterial({
color: 0x2be7ff,
emissive: 0x2be7ff,
emissiveIntensity: 1.1,
roughness: 0.3
})
);
head.position.copy(end).addScaledVector(tangent, -headLength / 2);
head.quaternion.setFromUnitVectors(Y_AXIS, tangent);
head.castShadow = true;
group.add(head);
const beadMaterial = new THREE.MeshBasicMaterial({
color: 0xb9f8ff
});
const beads = [];
for (let i = 0; i < 3; i++) {
const bead = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.065, 0),
beadMaterial
);
group.add(bead);
beads.push(bead);
}
scene.add(group);
return { group, curve, beads, directionSign };
}
// ------------------------------------------------------------------
// Conducting loop and stand
// ------------------------------------------------------------------
const loopX = 0.45;
const loopGroup = new THREE.Group();
loopGroup.position.x = loopX;
scene.add(loopGroup);
const loopMaterial = new THREE.MeshStandardMaterial({
color: 0xb8cada,
emissive: 0x12313d,
emissiveIntensity: 0.45,
metalness: 0.78,
roughness: 0.26
});
const loop = new THREE.Mesh(
new THREE.TorusGeometry(1.35, 0.105, 6, 40),
loopMaterial
);
// TorusGeometry initially lies in XY; this rotates its normal to +x.
loop.rotation.y = Math.PI / 2;
loop.castShadow = true;
loop.receiveShadow = true;
loopGroup.add(loop);
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.09, 0.12, 0.78, 8),
new THREE.MeshStandardMaterial({
color: 0x50677b,
metalness: 0.68,
roughness: 0.38
})
);
post.position.y = -1.68;
post.castShadow = true;
loopGroup.add(post);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.47, 0.57, 0.13, 10),
new THREE.MeshStandardMaterial({
color: 0x24394d,
metalness: 0.45,
roughness: 0.5
})
);
base.position.y = -2.02;
base.castShadow = true;
base.receiveShadow = true;
loopGroup.add(base);
// ------------------------------------------------------------------
// Faceted bar magnet: S half at -x, N half at +x
// ------------------------------------------------------------------
const magnet = new THREE.Group();
scene.add(magnet);
const southMaterial = new THREE.MeshStandardMaterial({
color: 0x3279d9,
emissive: 0x0c244c,
emissiveIntensity: 0.35,
roughness: 0.55,
metalness: 0.12,
flatShading: true
});
const northMaterial = new THREE.MeshStandardMaterial({
color: 0xf24f64,
emissive: 0x4c0c18,
emissiveIntensity: 0.35,
roughness: 0.55,
metalness: 0.12,
flatShading: true
});
const magnetGeometry = new THREE.CylinderGeometry(0.52, 0.52, 0.88, 8);
const southHalf = new THREE.Mesh(magnetGeometry, southMaterial);
southHalf.rotation.z = Math.PI / 2;
southHalf.position.x = -0.46;
southHalf.castShadow = true;
magnet.add(southHalf);
const northHalf = new THREE.Mesh(magnetGeometry, northMaterial);
northHalf.rotation.z = Math.PI / 2;
northHalf.position.x = 0.46;
northHalf.castShadow = true;
magnet.add(northHalf);
const seam = new THREE.Mesh(
new THREE.CylinderGeometry(0.525, 0.525, 0.055, 8),
new THREE.MeshStandardMaterial({
color: 0x182534,
metalness: 0.6,
roughness: 0.4
})
);
seam.rotation.z = Math.PI / 2;
magnet.add(seam);
const nLabel = makeLabel("N", "#ffffff", 0.38, 0.38);
nLabel.position.set(1.08, 0.02, 0);
magnet.add(nLabel);
const sLabel = makeLabel("S", "#ffffff", 0.38, 0.38);
sLabel.position.set(-1.08, 0.02, 0);
magnet.add(sLabel);
// Violet motion arrows above the magnet.
const motionForward = new THREE.Group();
makeArrow(
motionForward,
new THREE.Vector3(-0.52, 0.92, 0),
new THREE.Vector3(0.52, 0.92, 0),
0xb58cff,
0.027,
0.11
);
magnet.add(motionForward);
const motionBackward = new THREE.Group();
makeArrow(
motionBackward,
new THREE.Vector3(0.52, 0.92, 0),
new THREE.Vector3(-0.52, 0.92, 0),
0xb58cff,
0.027,
0.11
);
magnet.add(motionBackward);
// ------------------------------------------------------------------
// Field arrows and labels
// ------------------------------------------------------------------
const externalField = new THREE.Group();
scene.add(externalField);
// External field at the loop points in +x, away from the north pole.
makeArrow(
externalField,
new THREE.Vector3(-1.15, 0.48, 0.02),
new THREE.Vector3(2.15, 0.48, 0.02),
0xffc857,
0.036,
0.145
);
makeArrow(
externalField,
new THREE.Vector3(-0.95, -0.49, 0.32),
new THREE.Vector3(1.72, -0.49, 0.32),
0xffc857,
0.031,
0.125
);
const externalLabel = makeLabel("Bext = +x", "#ffc857", 1.45, 0.35);
externalLabel.position.set(1.72, 0.84, 0.05);
scene.add(externalLabel);
// Induced field while approaching is -x.
const inducedApproach = new THREE.Group();
makeArrow(
inducedApproach,
new THREE.Vector3(1.95, -0.02, -0.34),
new THREE.Vector3(-1.28, -0.02, -0.34),
0x2be7ff,
0.045,
0.17
);
scene.add(inducedApproach);
// During recession, the induced field is +x.
const inducedRecede = new THREE.Group();
makeArrow(
inducedRecede,
new THREE.Vector3(-1.28, -0.02, -0.34),
new THREE.Vector3(1.95, -0.02, -0.34),
0x2be7ff,
0.045,
0.17
);
scene.add(inducedRecede);
const inducedApproachLabel = makeLabel(
"Bind = −x",
"#2be7ff",
1.32,
0.35
);
inducedApproachLabel.position.set(-1.15, -0.76, -0.35);
scene.add(inducedApproachLabel);
const inducedRecedeLabel = makeLabel(
"Bind = +x",
"#2be7ff",
1.32,
0.35
);
inducedRecedeLabel.position.copy(inducedApproachLabel.position);
scene.add(inducedRecedeLabel);
// Loop-normal arrow.
const normalArrow = new THREE.Group();
makeArrow(
normalArrow,
new THREE.Vector3(-0.25, 1.98, 0),
new THREE.Vector3(1.25, 1.98, 0),
0xb58cff,
0.03,
0.12
);
scene.add(normalArrow);
const normalLabel = makeLabel("n = +x", "#b58cff", 1.12, 0.34);
normalLabel.position.set(0.5, 2.23, 0);
scene.add(normalLabel);
// Current arrows: CW while approaching and CCW while receding,
// as viewed from the +x side.
const currentApproach = createCurrentArrow(-1);
const currentRecede = createCurrentArrow(+1);
// ------------------------------------------------------------------
// Animation state
// ------------------------------------------------------------------
const clock = new THREE.Clock();
const midpointX = -2.55;
const amplitude = 0.72;
const angularSpeed = (Math.PI * 2) / 14;
const initialPhase = Math.PI * 0.35;
let elapsed = 0;
let paused = false;
let approaching = true;
const status = document.getElementById("status");
const statusText = document.getElementById("status-text");
const pauseButton = document.getElementById("pause");
function setState(nextApproaching) {
if (nextApproaching === approaching) return;
approaching = nextApproaching;
currentApproach.group.visible = approaching;
currentRecede.group.visible = !approaching;
inducedApproach.visible = approaching;
inducedRecede.visible = !approaching;
inducedApproachLabel.visible = approaching;
inducedRecedeLabel.visible = !approaching;
motionForward.visible = approaching;
motionBackward.visible = !approaching;
status.classList.toggle("receding", !approaching);
statusText.textContent = approaching
? "APPROACHING · dΦext/dt > 0 · Bind = −x · Iind CW from +x"
: "RECEDING · dΦext/dt < 0 · Bind = +x · Iind CCW from +x";
}
currentRecede.group.visible = false;
inducedRecede.visible = false;
inducedRecedeLabel.visible = false;
motionBackward.visible = false;
// ------------------------------------------------------------------
// Direct camera controls: drag to orbit, wheel to zoom
// ------------------------------------------------------------------
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraAzimuth -= deltaX * 0.0055;
cameraElevation = THREE.MathUtils.clamp(
cameraElevation + deltaY * 0.0045,
0.08,
1.08
);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (
event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius + event.deltaY * 0.008,
5.5,
15
);
updateCamera();
},
{ passive: false }
);
function resetCamera() {
cameraAzimuth = 0.76;
cameraElevation = 0.31;
cameraRadius = 9.6;
updateCamera();
}
document
.getElementById("reset-camera")
.addEventListener("click", resetCamera);
renderer.domElement.addEventListener("dblclick", resetCamera);
pauseButton.addEventListener("click", () => {
paused = !paused;
pauseButton.textContent = paused ? "Play" : "Pause";
});
document.getElementById("replay").addEventListener("click", () => {
elapsed = 0;
paused = false;
pauseButton.textContent = "Pause";
});
window.addEventListener("keydown", (event) => {
if (event.code === "Space") {
event.preventDefault();
pauseButton.click();
}
if (event.key.toLowerCase() === "r") {
resetCamera();
}
});
// ------------------------------------------------------------------
// Main loop
// ------------------------------------------------------------------
function animate() {
const delta = Math.min(clock.getDelta(), 0.05);
if (!paused) {
elapsed += delta;
}
const phase = initialPhase + elapsed * angularSpeed;
// Smooth back-and-forth motion. The first half is an approach.
magnet.position.x = midpointX - amplitude * Math.cos(phase);
const velocity = amplitude * angularSpeed * Math.sin(phase);
if (velocity > 0.015) {
setState(true);
} else if (velocity < -0.015) {
setState(false);
}
// Animated beads emphasize the current direction.
if (approaching) {
currentApproach.beads.forEach((bead, index) => {
const t =
(0.16 + index * 0.27 + elapsed * 0.2) % 1;
bead.position.copy(currentApproach.curve.getPointAt(t));
});
} else {
currentRecede.beads.forEach((bead, index) => {
const t =
(0.16 + index * 0.27 + elapsed * 0.2) % 1;
bead.position.copy(currentRecede.curve.getPointAt(t));
});
}
renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
</script>
</body>
</html>
```