Prompt specification
Build or customize the Three.js 3D scene "Charged-particle velocity-field triad" 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: Charged-particle velocity-field triad
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/charged-particle-velocity-field-triad-x1645
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring magnetic forces on moving charged particles. Place velocity, magnetic-field, and force arrows around a particle proxy; compute the cross-product direction and distinguish positive from negative charge explicitly. Low-poly.
Working Three.js Starter (charged-particle-velocity-field-triad-x1645):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Magnetic Force — Lorentz Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 20, 35, 0.82);
--border: rgba(148, 184, 220, 0.18);
--text: #eaf4ff;
--muted: #8ea6bf;
--cyan: #35e7ff;
--amber: #ffc857;
--magenta: #ff55d9;
--positive: #ff667a;
--negative: #568dff;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 42%, #11233a 0%, #07111f 52%, #030812 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
}
canvas {
display: block;
touch-action: none;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background: radial-gradient(circle, transparent 48%, rgba(0, 0, 0, 0.42) 100%);
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--border);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
.brand {
top: 20px;
left: 20px;
width: min(440px, calc(100vw - 40px));
padding: 18px 20px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 7px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.live-dot {
width: 7px;
height: 7px;
border-radius: 50%;
background: #61f7ad;
box-shadow: 0 0 13px #61f7ad;
}
h1 {
margin: 0;
font-size: clamp(21px, 3vw, 30px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.formula {
margin-top: 8px;
color: #c7d8ea;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 14px;
}
.hint {
margin-top: 9px;
color: var(--muted);
font-size: 11px;
}
.controls {
top: 20px;
right: 20px;
width: 278px;
padding: 16px;
}
.section-title {
margin-bottom: 11px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.segmented {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
margin-bottom: 17px;
}
button {
border: 1px solid rgba(148, 184, 220, 0.18);
border-radius: 10px;
padding: 10px 11px;
background: rgba(255, 255, 255, 0.045);
color: #c5d5e6;
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition: 150ms ease;
}
button:hover {
border-color: rgba(148, 184, 220, 0.42);
background: rgba(255, 255, 255, 0.08);
color: white;
}
button.active[data-charge="1"] {
border-color: rgba(255, 102, 122, 0.75);
background: rgba(255, 102, 122, 0.14);
color: #ff9aaa;
box-shadow: inset 0 0 18px rgba(255, 102, 122, 0.06);
}
button.active[data-charge="-1"] {
border-color: rgba(86, 141, 255, 0.78);
background: rgba(86, 141, 255, 0.14);
color: #9dbbff;
box-shadow: inset 0 0 18px rgba(86, 141, 255, 0.06);
}
.range-row {
margin-bottom: 15px;
}
.range-label {
display: flex;
justify-content: space-between;
margin-bottom: 8px;
color: #cbd9e8;
font-size: 12px;
}
output {
color: var(--amber);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
input[type="range"] {
width: 100%;
accent-color: var(--amber);
cursor: pointer;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 7px;
}
.button-row .wide {
grid-column: 1 / -1;
}
.status {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid rgba(148, 184, 220, 0.12);
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
#run-state {
color: #61f7ad;
}
.legend {
left: 20px;
bottom: 20px;
width: 260px;
padding: 15px 17px;
}
.legend-row {
display: flex;
align-items: center;
gap: 10px;
margin-top: 9px;
color: #c5d5e6;
font-size: 12px;
}
.swatch {
width: 22px;
height: 4px;
border-radius: 999px;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.swatch.round {
width: 11px;
height: 11px;
margin: 0 5px;
border-radius: 50%;
}
.legend strong {
color: white;
font-weight: 750;
}
.readout {
right: 20px;
bottom: 20px;
width: 310px;
padding: 16px 17px;
}
.charge-badge {
display: inline-flex;
align-items: center;
gap: 7px;
margin: 0 0 12px;
padding: 6px 9px;
border: 1px solid currentColor;
border-radius: 999px;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.charge-badge::before {
content: "";
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 10px currentColor;
}
.vector-row {
display: grid;
grid-template-columns: 60px 1fr;
align-items: center;
min-height: 25px;
border-bottom: 1px solid rgba(148, 184, 220, 0.08);
font-size: 11px;
}
.vector-row:last-of-type {
border-bottom: 0;
}
.vector-name {
color: var(--muted);
font-weight: 750;
}
.vector-value {
overflow: hidden;
color: #e7f2ff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.direction {
margin-top: 11px;
padding: 10px 11px;
border: 1px solid rgba(255, 85, 217, 0.2);
border-radius: 10px;
background: rgba(255, 85, 217, 0.065);
color: #ffc0ef;
font-size: 11px;
line-height: 1.5;
}
@media (max-width: 780px) {
.brand {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 14px 16px;
}
.controls {
top: auto;
right: 12px;
bottom: 12px;
width: 245px;
padding: 13px;
}
.legend,
.readout {
display: none;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="vignette"></div>
<section class="panel brand">
<div class="eyebrow"><span class="live-dot"></span> Interactive Lorentz field</div>
<h1>Magnetic Force Laboratory</h1>
<div class="formula">F = q (v × B)</div>
<div class="hint">Drag to orbit · scroll to zoom · the cyan v and amber B define the magenta force axis</div>
</section>
<section class="panel controls">
<div class="section-title">Particle proxy</div>
<div class="segmented" aria-label="Charge sign">
<button type="button" data-charge="1" class="active" aria-pressed="true">+q · Positive</button>
<button type="button" data-charge="-1" aria-pressed="false">−q · Negative</button>
</div>
<div class="range-row">
<label class="range-label" for="field-strength">
<span>Magnetic field strength</span>
<output id="field-output">1.20 T</output>
</label>
<input id="field-strength" type="range" min="0.4" max="2.4" value="1.2" step="0.05" />
</div>
<div class="button-row">
<button type="button" id="flip-field">Flip B</button>
<button type="button" id="pause">Pause</button>
<button type="button" id="reset-camera" class="wide">Reset camera</button>
</div>
<div class="status">
<span>Uniform field</span>
<span id="run-state">Running</span>
</div>
</section>
<section class="panel legend">
<div class="section-title">Scene key</div>
<div class="legend-row"><span class="swatch" style="color:var(--cyan)"></span><strong>v</strong> velocity</div>
<div class="legend-row"><span class="swatch" style="color:var(--amber)"></span><strong>B</strong> magnetic field</div>
<div class="legend-row"><span class="swatch" style="color:var(--magenta)"></span><strong>F</strong> force / cross-product normal</div>
<div class="legend-row"><span class="swatch round" style="color:var(--positive)"></span><strong>+q</strong> positive charge</div>
<div class="legend-row"><span class="swatch round" style="color:var(--negative)"></span><strong>−q</strong> negative charge</div>
</section>
<section class="panel readout">
<div class="section-title">Live vector solver</div>
<div id="charge-badge" class="charge-badge" style="color:var(--positive)">Positive charge</div>
<div class="vector-row">
<span class="vector-name">Velocity</span>
<span id="v-value" class="vector-value">v = (1.00, 0.00, 0.00)</span>
</div>
<div class="vector-row">
<span class="vector-name">Field</span>
<span id="b-value" class="vector-value">B = (0.00, 1.20, 0.00)</span>
</div>
<div class="vector-row">
<span class="vector-name">v × B</span>
<span id="cross-value" class="vector-value">(0.00, 0.00, 1.20)</span>
</div>
<div class="vector-row">
<span class="vector-name">Force</span>
<span id="force-value" class="vector-value">F = (0.00, 0.00, 1.20)</span>
</div>
<div id="direction-summary" class="direction">
<strong>Right-hand rule:</strong> v × B points +Z. Since q is positive,
F follows +Z.
</div>
</section>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const COLORS = {
velocity: 0x35e7ff,
field: 0xffc857,
force: 0xff55d9,
positive: 0xff667a,
negative: 0x568dff,
grid: 0x24425b,
gridMinor: 0x16283b
};
const state = {
charge: 1,
fieldStrength: 1.2,
fieldSign: 1,
paused: false
};
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 15, 31);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
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;
document.getElementById("scene").appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraTarget = new THREE.Vector3(0, 0.15, 0);
const cameraState = {
radius: 14.5,
theta: 0.72,
phi: 1.04
};
function updateCamera() {
const s = Math.sin(cameraState.phi);
camera.position.set(
cameraTarget.x + cameraState.radius * s * Math.sin(cameraState.theta),
cameraTarget.y + cameraState.radius * Math.cos(cameraState.phi),
cameraTarget.z + cameraState.radius * s * Math.cos(cameraState.theta)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraState.radius = 14.5;
cameraState.theta = 0.72;
cameraState.phi = 1.04;
updateCamera();
}
updateCamera();
// Custom camera controls: no external controls/addons.
let dragging = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.006,
0.22,
Math.PI - 0.22
);
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("wheel", (event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7,
25
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("contextmenu", (event) => event.preventDefault());
scene.add(new THREE.HemisphereLight(0xa9d8ff, 0x101827, 2.0));
const keyLight = new THREE.DirectionalLight(0xffffff, 2.6);
keyLight.position.set(5, 9, 7);
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x568dff, 1.8);
rimLight.position.set(-7, 3, -5);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xff8fcf, 8, 16, 2);
warmLight.position.set(4, 2, 4);
scene.add(warmLight);
const grid = new THREE.GridHelper(20, 20, COLORS.grid, COLORS.gridMinor);
grid.position.y = -1.65;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
// Low-poly vector arrow with a cylindrical shaft and six-sided head.
class VectorArrow {
constructor(color, radius = 0.04, headRadius = 0.14, headHeight = 0.34) {
this.group = new THREE.Group();
this.radius = radius;
this.headRadius = headRadius;
this.headHeight = headHeight;
const material = new THREE.MeshBasicMaterial({
color,
toneMapped: false
});
this.shaft = new THREE.Mesh(
new THREE.CylinderGeometry(radius, radius, 1, 6),
material
);
this.head = new THREE.Mesh(
new THREE.ConeGeometry(headRadius, headHeight, 6),
material
);
this.group.add(this.shaft, this.head);
scene.add(this.group);
}
get position() { return this.group.position; }
update(direction, length) {
const dir = direction.clone().normalize();
const headLength = Math.min(this.headHeight, length * 0.34);
const shaftLength = Math.max(0.01, length - headLength);
this.group.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
dir
);
this.shaft.scale.y = shaftLength;
this.shaft.position.y = shaftLength * 0.5;
this.head.scale.set(
1,
headLength / this.headHeight,
1
);
this.head.position.y = shaftLength + headLength * 0.5;
}
}
// Canvas-backed, billboarded labels.
function roundedRect(ctx, x, y, width, height, radius) {
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
}
function createLabel(text, color, worldWidth = 0.9, worldHeight = 0.34) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 160;
const ctx = canvas.getContext("2d");
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,
toneMapped: false,
fog: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(worldWidth, worldHeight, 1);
sprite.renderOrder = 20;
function setText(nextText, nextColor = color) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgba(4, 10, 20, 0.88)";
ctx.strokeStyle = nextColor;
ctx.lineWidth = 7;
roundedRect(ctx, 10, 14, 492, 132, 28);
ctx.fill();
ctx.stroke();
ctx.fillStyle = nextColor;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.font = `800 ${nextText.length > 1 ? 66 : 78}px ui-monospace, monospace`;
ctx.fillText(nextText, 256, 82);
texture.needsUpdate = true;
}
setText(text);
sprite.userData.setText = setText;
return sprite;
}
// Central particle proxy.
const proxy = new THREE.Group();
proxy.position.set(0, 0, 0);
scene.add(proxy);
const proxyMaterial = new THREE.MeshStandardMaterial({
color: COLORS.positive,
emissive: 0x4b1020,
emissiveIntensity: 0.7,
roughness: 0.42,
metalness: 0.12,
flatShading: true
});
const proxyMesh = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.58, 1),
proxyMaterial
);
proxy.add(proxyMesh);
const haloMaterial = new THREE.MeshBasicMaterial({
color: COLORS.positive,
transparent: true,
opacity: 0.75,
toneMapped: false
});
const haloA = new THREE.Mesh(
new THREE.TorusGeometry(0.88, 0.025, 4, 32),
haloMaterial
);
haloA.rotation.x = Math.PI * 0.5;
proxy.add(haloA);
const haloB = new THREE.Mesh(
new THREE.TorusGeometry(0.98, 0.018, 4, 32),
haloMaterial
);
haloB.rotation.y = Math.PI * 0.5;
proxy.add(haloB);
const chargeLabel = createLabel("+q", "#ff667a", 0.92, 0.36);
chargeLabel.position.set(-0.92, 0.78, 0.12);
proxy.add(chargeLabel);
// Main arrows.
const velocityArrow = new VectorArrow(COLORS.velocity, 0.052, 0.18, 0.42);
const fieldArrow = new VectorArrow(COLORS.field, 0.052, 0.18, 0.42);
const forceArrow = new VectorArrow(COLORS.force, 0.055, 0.19, 0.44);
const velocityLabel = createLabel("v", "#35e7ff", 0.58, 0.30);
const fieldLabel = createLabel("B", "#ffc857", 0.58, 0.30);
const forceLabel = createLabel("F", "#ff55d9", 0.58, 0.30);
scene.add(velocityLabel, fieldLabel, forceLabel);
// Translucent plane spanned by v and B. Its normal is the cross-product direction.
const guideGeometry = new THREE.BufferGeometry();
guideGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(18), 3)
);
const guideMesh = new THREE.Mesh(
guideGeometry,
new THREE.MeshBasicMaterial({
color: 0xc979ff,
transparent: true,
opacity: 0.045,
side: THREE.DoubleSide,
depthWrite: false
})
);
const guideLineGeometry = new THREE.BufferGeometry();
guideLineGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(12), 3)
);
const guideLine = new THREE.LineLoop(
guideLineGeometry,
new THREE.LineBasicMaterial({
color: 0xd58aff,
transparent: true,
opacity: 0.34
})
);
scene.add(guideMesh, guideLine);
// Subtle uniform-field lines running along the field axis.
const fieldLineGroup = new THREE.Group();
scene.add(fieldLineGroup);
const fieldLinePositions = [];
for (const x of [-6, 0, 6]) {
for (const z of [-6, 0, 6]) {
fieldLinePositions.push(x, -2.6, z, x, 4.6, z);
const cone = new THREE.Mesh(
new THREE.ConeGeometry(0.09, 0.3, 6),
new THREE.MeshBasicMaterial({
color: COLORS.field,
transparent: true,
opacity: 0.42,
toneMapped: false
})
);
cone.position.set(x, 4.05, z);
fieldLineGroup.add(cone);
}
}
const fieldLineGeometry = new THREE.BufferGeometry();
fieldLineGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(fieldLinePositions, 3)
);
fieldLineGroup.add(
new THREE.LineSegments(
fieldLineGeometry,
new THREE.LineBasicMaterial({
color: COLORS.field,
transparent: true,
opacity: 0.095
})
)
);
// Moving positive and negative charges in the uniform field.
const particleGeometry = new THREE.IcosahedronGeometry(0.17, 0);
const TRAIL_COUNT = 72;
const particleSpecs = [
{ c: [-4.2, -2.2], r: 1.25, theta: 0.2, q: 1, y: -0.25 },
{ c: [-0.8, -5.0], r: 1.45, theta: 1.1, q: -1, y: 0.38 },
{ c: [ 3.2, -4.1], r: 1.00, theta: 2.0, q: 1, y: -0.50 },
{ c: [ 5.2, 0.2], r: 1.30, theta: 0.8, q: -1, y: 0.12 },
{ c: [ 3.0, 4.0], r: 1.35, theta: 2.8, q: 1, y: 0.58 },
{ c: [-1.2, 5.0], r: 0.95, theta: 1.5, q: -1, y: -0.38 },
{ c: [-5.0, 2.5], r: 1.15, theta: 2.4, q: 1, y: 0.24 },
{ c: [-6.0, -3.2], r: 0.85, theta: 0.5, q: -1, y: -0.62 }
];
const movingParticles = particleSpecs.map((spec, index) => {
const chargeColor = spec.q > 0 ? COLORS.positive : COLORS.negative;
const material = new THREE.MeshStandardMaterial({
color: chargeColor,
emissive: chargeColor,
emissiveIntensity: 0.38,
roughness: 0.48,
metalness: 0.05,
flatShading: true
});
const mesh = new THREE.Mesh(particleGeometry, material);
scene.add(mesh);
const velocityArrow = new VectorArrow(COLORS.velocity, 0.022, 0.075, 0.18);
const forceArrow = new VectorArrow(COLORS.force, 0.024, 0.08, 0.19);
const signLabel = createLabel(
spec.q > 0 ? "+" : "−",
spec.q > 0 ? "#ff667a" : "#568dff",
0.38,
0.25
);
scene.add(signLabel);
const trailArray = new Float32Array(TRAIL_COUNT * 3);
const thetaDot = spec.q * state.fieldSign * state.fieldStrength;
for (let i = 0; i < TRAIL_COUNT; i++) {
const angle = spec.theta - thetaDot * (TRAIL_COUNT - 1 - i) * 0.018;
trailArray[i * 3] = spec.c[0] + spec.r * Math.cos(angle);
trailArray[i * 3 + 1] = spec.y;
trailArray[i * 3 + 2] = spec.c[1] + spec.r * Math.sin(angle);
}
const trailGeometry = new THREE.BufferGeometry();
trailGeometry.setAttribute(
"position",
new THREE.BufferAttribute(trailArray, 3).setUsage(THREE.DynamicDrawUsage)
);
const trail = new THREE.Line(
trailGeometry,
new THREE.LineBasicMaterial({
color: chargeColor,
transparent: true,
opacity: 0.5
})
);
trail.frustumCulled = false;
scene.add(trail);
return {
...spec,
index,
mesh,
velocityArrow,
forceArrow,
signLabel,
trail,
trailArray,
position: new THREE.Vector3(),
velocity: new THREE.Vector3()
};
});
const ui = {
fieldInput: document.getElementById("field-strength"),
fieldOutput: document.getElementById("field-output"),
flipField: document.getElementById("flip-field"),
pause: document.getElementById("pause"),
resetCamera: document.getElementById("reset-camera"),
runState: document.getElementById("run-state"),
chargeBadge: document.getElementById("charge-badge"),
vValue: document.getElementById("v-value"),
bValue: document.getElementById("b-value"),
crossValue: document.getElementById("cross-value"),
forceValue: document.getElementById("force-value"),
directionSummary: document.getElementById("direction-summary"),
chargeButtons: [...document.querySelectorAll("[data-charge]")]
};
function vectorText(vector) {
return `(${vector.x.toFixed(2)}, ${vector.y.toFixed(2)}, ${vector.z.toFixed(2)})`;
}
function directionText(vector) {
const values = [
{ axis: "X", value: vector.x },
{ axis: "Y", value: vector.y },
{ axis: "Z", value: vector.z }
];
values.sort((a, b) => Math.abs(b.value) - Math.abs(a.value));
const dominant = values[0];
if (Math.abs(dominant.value) < 0.0001) return "zero";
return `${dominant.value >= 0 ? "+" : "−"}${dominant.axis}`;
}
function setCharge(charge) {
state.charge = charge;
const positive = charge > 0;
const color = positive ? "#ff667a" : "#568dff";
proxyMaterial.color.setHex(positive ? COLORS.positive : COLORS.negative);
proxyMaterial.emissive.setHex(positive ? 0x4b1020 : 0x102858);
haloMaterial.color.setHex(positive ? COLORS.positive : COLORS.negative);
chargeLabel.userData.setText(positive ? "+q" : "−q", color);
ui.chargeButtons.forEach((button) => {
const active = Number(button.dataset.charge) === charge;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
ui.chargeBadge.style.color = color;
ui.chargeBadge.textContent = positive ? "Positive charge · +q" : "Negative charge · −q";
}
ui.chargeButtons.forEach((button) => {
button.addEventListener("click", () => {
setCharge(Number(button.dataset.charge));
});
});
ui.fieldInput.addEventListener("input", () => {
state.fieldStrength = Number(ui.fieldInput.value);
ui.fieldOutput.textContent = `${state.fieldStrength.toFixed(2)} T`;
});
ui.flipField.addEventListener("click", () => {
state.fieldSign *= -1;
fieldLineGroup.rotation.x = state.fieldSign > 0 ? 0 : Math.PI;
});
ui.pause.addEventListener("click", () => {
state.paused = !state.paused;
ui.pause.textContent = state.paused ? "Resume" : "Pause";
ui.runState.textContent = state.paused ? "Paused" : "Running";
ui.runState.style.color = state.paused ? "#ffc857" : "#61f7ad";
});
ui.resetCamera.addEventListener("click", resetCamera);
const mainVelocity = new THREE.Vector3(1, 0, 0);
const mainField = new THREE.Vector3(0, 1, 0);
const crossVector = new THREE.Vector3();
const forceVector = new THREE.Vector3();
function updateMainScene() {
mainField.set(0, state.fieldSign, 0);
const B = mainField.clone().multiplyScalar(state.fieldStrength);
crossVector.crossVectors(mainVelocity, B);
forceVector.copy(crossVector).multiplyScalar(state.charge);
const velocityLength = 2.55;
const fieldLength = 2.70;
const forceLength = 1.12 + state.fieldStrength * 0.43;
velocityArrow.position.copy(proxy.position);
fieldArrow.position.copy(proxy.position);
forceArrow.position.copy(proxy.position);
velocityArrow.update(mainVelocity, velocityLength);
fieldArrow.update(mainField, fieldLength);
forceArrow.update(forceVector, forceLength);
velocityLabel.position.copy(proxy.position)
.addScaledVector(mainVelocity, velocityLength + 0.34);
fieldLabel.position.copy(proxy.position)
.addScaledVector(mainField, fieldLength + 0.34);
forceLabel.position.copy(proxy.position)
.addScaledVector(forceVector.clone().normalize(), forceLength + 0.38);
// Rebuild the v–B guide plane.
const a = mainVelocity.clone().multiplyScalar(1.42);
const b = mainField.clone().multiplyScalar(1.42);
const corners = [
a.clone().add(b),
a.clone().sub(b).negate(),
a.clone().negate().sub(b),
a.clone().sub(b)
];
const planePositions = guideGeometry.attributes.position.array;
const triangles = [0, 1, 2, 0, 2, 3];
for (let i = 0; i < triangles.length; i++) {
const corner = corners[triangles[i]];
planePositions[i * 3] = corner.x;
planePositions[i * 3 + 1] = corner.y;
planePositions[i * 3 + 2] = corner.z;
}
guideGeometry.attributes.position.needsUpdate = true;
guideGeometry.computeVertexNormals();
const linePositions = guideLineGeometry.attributes.position.array;
corners.forEach((corner, i) => {
linePositions[i * 3] = corner.x;
linePositions[i * 3 + 1] = corner.y;
linePositions[i * 3 + 2] = corner.z;
});
guideLineGeometry.attributes.position.needsUpdate = true;
ui.vValue.textContent = `v = ${vectorText(mainVelocity)}`;
ui.bValue.textContent = `B = ${vectorText(B)}`;
ui.crossValue.textContent = vectorText(crossVector);
ui.forceValue.textContent = `F = ${vectorText(forceVector)}`;
const chargeName = state.charge > 0 ? "positive" : "negative";
ui.directionSummary.innerHTML =
`<strong>Right-hand rule:</strong> v × B points ${directionText(crossVector)}. ` +
`Since q is ${chargeName}, F follows ${directionText(forceVector)}.`;
}
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.033);
updateMainScene();
if (!state.paused) {
const B = new THREE.Vector3(0, state.fieldSign * state.fieldStrength, 0);
for (const particle of movingParticles) {
const thetaDot =
particle.q * state.fieldSign * state.fieldStrength;
particle.theta += thetaDot * dt;
particle.position.set(
particle.c[0] + particle.r * Math.cos(particle.theta),
particle.y,
particle.c[1] + particle.r * Math.sin(particle.theta)
);
const tangent = new THREE.Vector3(
-Math.sin(particle.theta),
0,
Math.cos(particle.theta)
);
particle.velocity.copy(tangent).multiplyScalar(
particle.r * thetaDot
);
const force = new THREE.Vector3()
.crossVectors(particle.velocity, B)
.multiplyScalar(particle.q);
particle.mesh.position.copy(particle.position);
particle.mesh.rotation.x += dt * 0.9;
particle.mesh.rotation.y += dt * 1.3;
particle.velocityArrow.position.copy(particle.position);
particle.velocityArrow.update(
particle.velocity,
0.62 + Math.min(0.18, particle.velocity.length() * 0.06)
);
particle.forceArrow.position.copy(particle.position);
particle.forceArrow.update(
force,
0.45 + Math.min(0.48, force.length() * 0.20)
);
particle.signLabel.position.copy(particle.position);
particle.signLabel.position.y += 0.34;
const trail = particle.trailArray;
for (let i = 0; i < TRAIL_COUNT - 1; i++) {
trail[i * 3] = trail[(i + 1) * 3];
trail[i * 3 + 1] = trail[(i + 1) * 3 + 1];
trail[i * 3 + 2] = trail[(i + 1) * 3 + 2];
}
trail[(TRAIL_COUNT - 1) * 3] = particle.position.x;
trail[(TRAIL_COUNT - 1) * 3 + 1] = particle.position.y;
trail[(TRAIL_COUNT - 1) * 3 + 2] = particle.position.z;
particle.trail.geometry.attributes.position.needsUpdate = true;
}
}
haloA.rotation.z += dt * 0.22;
haloB.rotation.x -= dt * 0.17;
const pulse = 1 + Math.sin(clock.elapsedTime * 2.2) * 0.035;
proxyMesh.scale.setScalar(pulse);
haloA.scale.setScalar(1 + Math.sin(clock.elapsedTime * 1.7) * 0.05);
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
setCharge(1);
updateMainScene();
animate();
</script>
</body>
</html>
```