Prompt specification
Build or customize the Three.js 3D scene "Spring and movable mass scale" 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: Spring and movable mass scale
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/spring-and-movable-mass-scale-x1429
Scene Description Prompt:
Make one HTML file using Three.js from cdnjs for this low-poly scene: Build a spring attached to a wall and a sliding mass with displacement markers; display restoring force opposite displacement under a stated Hooke-law range.
Working Three.js Starter (spring-and-movable-mass-scale-x1429):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hooke's Law — Spring and Sliding Mass</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 24, 43, 0.88);
--panel-border: rgba(153, 211, 255, 0.2);
--text: #edf7ff;
--muted: #9eb4ca;
--cyan: #43d9ff;
--orange: #ff865f;
--mint: #75efbd;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
background:
radial-gradient(circle at 50% 25%, #173153 0%, #0a1729 42%, #050b14 100%);
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
.brand {
position: fixed;
top: 24px;
left: 26px;
z-index: 5;
pointer-events: none;
text-shadow: 0 2px 18px rgba(0, 0, 0, 0.55);
}
.brand h1 {
margin: 0;
font-size: clamp(22px, 3vw, 38px);
letter-spacing: -0.035em;
}
.brand p {
margin: 7px 0 0;
color: var(--muted);
font-size: 14px;
}
.brand strong {
color: var(--cyan);
font-weight: 650;
}
.panel {
position: fixed;
top: 22px;
right: 22px;
z-index: 10;
width: min(340px, calc(100vw - 44px));
padding: 18px;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
box-shadow:
0 22px 60px rgba(0, 0, 0, 0.32),
inset 0 1px 0 rgba(255, 255, 255, 0.04);
backdrop-filter: blur(16px);
}
.panel-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 14px;
}
.panel-title {
font-size: 13px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
color: #c9e7fa;
}
.status {
display: inline-flex;
align-items: center;
gap: 7px;
color: var(--mint);
font-size: 12px;
white-space: nowrap;
}
.status::before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: currentColor;
box-shadow: 0 0 12px currentColor;
}
.range-box {
padding: 12px 13px;
border: 1px solid rgba(117, 239, 189, 0.2);
border-radius: 12px;
background: rgba(117, 239, 189, 0.055);
}
.range-box .label {
color: var(--muted);
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.range-box .value {
margin-top: 4px;
color: var(--mint);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 17px;
font-weight: 700;
}
.slider-row {
margin-top: 17px;
}
.slider-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 9px;
}
.slider-heading label {
color: var(--muted);
font-size: 13px;
}
output {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 17px;
font-weight: 700;
}
input[type="range"] {
width: 100%;
height: 24px;
margin: 0;
accent-color: var(--cyan);
cursor: pointer;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 8px;
margin-top: 11px;
}
button {
min-height: 35px;
border: 1px solid rgba(160, 210, 240, 0.18);
border-radius: 9px;
color: #d9edfb;
background: rgba(255, 255, 255, 0.045);
font: inherit;
font-size: 12px;
cursor: pointer;
transition:
background 140ms ease,
border-color 140ms ease,
transform 140ms ease;
}
button:hover {
background: rgba(67, 217, 255, 0.11);
border-color: rgba(67, 217, 255, 0.45);
}
button:active {
transform: translateY(1px);
}
.readouts {
display: grid;
gap: 9px;
margin-top: 17px;
}
.readout {
display: flex;
align-items: center;
justify-content: space-between;
gap: 15px;
min-height: 38px;
padding: 8px 11px;
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
}
.readout span:first-child {
color: var(--muted);
font-size: 13px;
}
.readout strong {
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 15px;
}
#forceValue {
color: var(--orange);
}
.direction {
padding-top: 3px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
text-align: right;
}
.legend {
position: fixed;
left: 26px;
bottom: 24px;
z-index: 5;
display: flex;
flex-wrap: wrap;
gap: 9px 18px;
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 12px;
background: rgba(7, 17, 31, 0.6);
backdrop-filter: blur(10px);
pointer-events: none;
}
.legend-item {
display: flex;
align-items: center;
gap: 8px;
color: #c7d9e8;
font-size: 12px;
}
.swatch {
width: 22px;
height: 3px;
border-radius: 2px;
}
.swatch.cyan {
background: var(--cyan);
box-shadow: 0 0 9px rgba(67, 217, 255, 0.55);
}
.swatch.orange {
background: var(--orange);
box-shadow: 0 0 9px rgba(255, 134, 95, 0.55);
}
.hint {
position: fixed;
right: 24px;
bottom: 24px;
z-index: 5;
color: rgba(214, 231, 246, 0.7);
font-size: 12px;
pointer-events: none;
text-shadow: 0 2px 12px #000;
}
@media (max-width: 760px) {
.brand {
top: 15px;
left: 16px;
}
.brand p {
display: none;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
padding: 14px;
}
.panel-header,
.range-box {
display: none;
}
.readouts {
grid-template-columns: 1fr 1fr;
margin-top: 12px;
}
.readout:last-of-type,
.direction {
grid-column: 1 / -1;
}
.legend {
top: 66px;
bottom: auto;
left: 16px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<div id="scene" aria-label="Interactive three-dimensional Hooke's law scene"></div>
<header class="brand">
<h1>Hooke's Law</h1>
<p><strong>Spring</strong> + sliding mass · restoring force simulation</p>
</header>
<section class="panel" aria-label="Simulation controls and readings">
<div class="panel-header">
<div class="panel-title">Spring Model</div>
<div class="status" id="status">In Hooke range</div>
</div>
<div class="range-box">
<div class="label">Stated Hooke-law range</div>
<div class="value">−0.40 m ≤ x ≤ +0.40 m</div>
</div>
<div class="slider-row">
<div class="slider-heading">
<label for="displacement">Displacement</label>
<output id="xValue" for="displacement">+0.00 m</output>
</div>
<input
id="displacement"
type="range"
min="-0.4"
max="0.4"
step="0.01"
value="0"
aria-label="Mass displacement in meters"
>
<div class="buttons">
<button type="button" data-displacement="-0.4">−0.40 m</button>
<button type="button" data-displacement="0">Equilibrium</button>
<button type="button" data-displacement="0.4">+0.40 m</button>
</div>
</div>
<div class="readouts" aria-live="polite">
<div class="readout">
<span>Spring constant</span>
<strong>k = 12.0 N/m</strong>
</div>
<div class="readout">
<span>Restoring force</span>
<strong id="forceValue">0.00 N</strong>
</div>
<div class="readout">
<span>Mass</span>
<strong>2.0 kg</strong>
</div>
<div class="direction" id="directionValue">
Zero displacement at equilibrium.
</div>
</div>
</section>
<div class="legend" aria-hidden="true">
<div class="legend-item">
<span class="swatch cyan"></span>
Displacement x
</div>
<div class="legend-item">
<span class="swatch orange"></span>
Restoring force Fᵣ = −kx
</div>
</div>
<div class="hint">
Drag the mass · drag background to orbit · wheel to zoom
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ------------------------------------------------------------
// Model constants
// ------------------------------------------------------------
const K = 12.0; // N/m
const MASS = 2.0; // kg
const MIN_X = -0.40; // m
const MAX_X = 0.40; // m
const WORLD_SCALE = 2.0; // scene units per meter
const REST_X = -0.60; // equilibrium mass-center position
const SPRING_START = -2.90;
const SPRING_Y = 0.05;
const MASS_HALF_WIDTH = 0.525;
const host = document.querySelector("#scene");
const slider = document.querySelector("#displacement");
const xOutput = document.querySelector("#xValue");
const forceOutput = document.querySelector("#forceValue");
const directionOutput = document.querySelector("#directionValue");
const statusOutput = document.querySelector("#status");
let displacement = 0;
let springMesh = null;
// ------------------------------------------------------------
// Renderer, scene, camera
// ------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
host.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x091426, 9, 19);
const camera = new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
0.1,
100
);
// Custom camera orbit state: no Three.js examples/addons are used.
const cameraTarget = new THREE.Vector3(-1.10, -0.05, 0);
let cameraRadius = 8.0;
let cameraTheta = 0.10;
let cameraPhi = 1.25;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.sin(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.cos(cameraTheta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
// ------------------------------------------------------------
// Lighting
// ------------------------------------------------------------
const hemisphere = new THREE.HemisphereLight(
0xbfe9ff,
0x182235,
2.1
);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.0);
keyLight.position.set(-2.0, 7.0, 5.0);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 6;
keyLight.shadow.camera.bottom = -6;
keyLight.shadow.camera.near = 0.1;
keyLight.shadow.camera.far = 20;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x55bfff, 1.5);
rimLight.position.set(4, 2, -4);
scene.add(rimLight);
const orangeLight = new THREE.PointLight(0xff754f, 12, 8);
orangeLight.position.set(1.5, 1.5, 2.2);
scene.add(orangeLight);
// ------------------------------------------------------------
// Materials and helpers
// ------------------------------------------------------------
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.7,
metalness: 0.05,
flatShading: true,
...options
});
}
function addBox(parent, size, position, material) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
material
);
mesh.position.copy(position);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinderBetween(
parent,
start,
end,
radius,
material,
radialSegments = 8
) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const midpoint = new THREE.Vector3()
.addVectors(start, end)
.multiplyScalar(0.5);
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(
radius,
radius,
length,
radialSegments,
1,
false
),
material
);
mesh.position.copy(midpoint);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
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 createLabel(
initialText,
accent = "#ffffff",
scale = new THREE.Vector2(1.2, 0.30)
) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 128;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.copy(scale);
sprite.renderOrder = 30;
function setText(text) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(5, 13, 25, 0.88)";
roundedRect(context, 5, 8, 502, 112, 24);
context.fill();
context.strokeStyle = accent;
context.lineWidth = 4;
roundedRect(context, 5, 8, 502, 112, 24);
context.stroke();
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = accent;
let fontSize = 43;
context.font = `700 ${fontSize}px system-ui, sans-serif`;
const measured = context.measureText(text).width;
if (measured > 455) {
fontSize = Math.max(25, fontSize * (455 / measured));
context.font = `700 ${fontSize}px system-ui, sans-serif`;
}
context.fillText(text, 256, 65);
texture.needsUpdate = true;
}
setText(initialText);
return {
sprite,
setText
};
}
// ------------------------------------------------------------
// Floor and grid
// ------------------------------------------------------------
const floorMaterial = standardMaterial(0x0c192a, {
roughness: 0.95,
metalness: 0
});
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 24),
floorMaterial
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -1.30;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(
16,
32,
0x31516d,
0x1a3046
);
grid.position.y = -1.285;
grid.material.transparent = true;
grid.material.opacity = 0.45;
scene.add(grid);
// ------------------------------------------------------------
// Wall and anchor
// ------------------------------------------------------------
const wallMaterial = standardMaterial(0x263b54, {
roughness: 0.9
});
const wall = addBox(
scene,
new THREE.Vector3(0.36, 3.2, 2.5),
new THREE.Vector3(-3.30, 0.15, 0),
wallMaterial
);
const wallEdgeMaterial = new THREE.LineBasicMaterial({
color: 0x5f7d99,
transparent: true,
opacity: 0.5
});
const wallEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(wall.geometry),
wallEdgeMaterial
);
wall.add(wallEdges);
const brickMaterialA = standardMaterial(0x304963);
const brickMaterialB = standardMaterial(0x293f57);
// Low-poly masonry details on the spring-facing side.
for (let row = 0; row < 5; row++) {
for (let col = 0; col < 3; col++) {
const brick = addBox(
scene,
new THREE.Vector3(0.045, 0.43, 0.64),
new THREE.Vector3(
-3.095,
-1.02 + row * 0.53,
-0.78 + col * 0.78
),
(row + col) % 2 === 0
? brickMaterialA
: brickMaterialB
);
brick.castShadow = false;
}
}
const steelMaterial = standardMaterial(0x90a9bd, {
metalness: 0.7,
roughness: 0.28
});
const anchorPlate = addBox(
scene,
new THREE.Vector3(0.13, 0.56, 0.56),
new THREE.Vector3(-3.07, SPRING_Y, 0),
steelMaterial
);
anchorPlate.castShadow = true;
addCylinderBetween(
scene,
new THREE.Vector3(-3.03, SPRING_Y, 0),
new THREE.Vector3(SPRING_START, SPRING_Y, 0),
0.085,
steelMaterial,
10
);
const anchorRing = new THREE.Mesh(
new THREE.TorusGeometry(0.13, 0.035, 6, 12),
steelMaterial
);
anchorRing.rotation.y = Math.PI / 2;
anchorRing.position.set(SPRING_START, SPRING_Y, 0);
anchorRing.castShadow = true;
scene.add(anchorRing);
// ------------------------------------------------------------
// Track
// ------------------------------------------------------------
const railMaterial = standardMaterial(0x637b91, {
metalness: 0.75,
roughness: 0.32
});
addCylinderBetween(
scene,
new THREE.Vector3(-2.45, -0.72, 0),
new THREE.Vector3(0.72, -0.72, 0),
0.055,
railMaterial,
10
);
const supportMaterial = standardMaterial(0x31475d);
for (const x of [-2.20, -1.05, 0.48]) {
addCylinderBetween(
scene,
new THREE.Vector3(x, -1.25, 0),
new THREE.Vector3(x, -0.72, 0),
0.045,
supportMaterial,
8
);
addBox(
scene,
new THREE.Vector3(0.32, 0.08, 0.42),
new THREE.Vector3(x, -1.25, 0),
supportMaterial
);
}
// ------------------------------------------------------------
// Sliding mass
// ------------------------------------------------------------
const massGroup = new THREE.Group();
scene.add(massGroup);
const massMaterial = standardMaterial(0x287ea3, {
roughness: 0.48,
metalness: 0.28,
emissive: 0x08283a,
emissiveIntensity: 0.45
});
const massBody = addBox(
massGroup,
new THREE.Vector3(1.05, 1.0, 1.05),
new THREE.Vector3(0, 0.05, 0),
massMaterial
);
const massEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(massBody.geometry),
new THREE.LineBasicMaterial({
color: 0x78c7e9,
transparent: true,
opacity: 0.75
})
);
massBody.add(massEdges);
const accentMaterial = standardMaterial(0x64d8f7, {
metalness: 0.3,
roughness: 0.4,
emissive: 0x0b3c4d,
emissiveIntensity: 0.35
});
addBox(
massGroup,
new THREE.Vector3(0.70, 0.36, 0.035),
new THREE.Vector3(0, 0.08, 0.54),
accentMaterial
);
addBox(
massGroup,
new THREE.Vector3(0.72, 0.10, 0.70),
new THREE.Vector3(0, 0.59, 0),
steelMaterial
);
const boltMaterial = standardMaterial(0xb3c6d4, {
metalness: 0.8,
roughness: 0.25
});
for (const x of [-0.36, 0.36]) {
const bolt = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.055, 0.04, 6),
boltMaterial
);
bolt.rotation.x = Math.PI / 2;
bolt.position.set(x, 0.08, 0.575);
massGroup.add(bolt);
}
const wheelMaterial = standardMaterial(0x172334, {
roughness: 0.72,
metalness: 0.2
});
for (const z of [-0.36, 0.36]) {
const wheel = new THREE.Mesh(
new THREE.CylinderGeometry(0.14, 0.14, 0.16, 10),
wheelMaterial
);
wheel.rotation.x = Math.PI / 2;
wheel.position.set(0, -0.58, z);
wheel.castShadow = true;
massGroup.add(wheel);
}
const massLabel = createLabel(
`m = ${MASS.toFixed(1)} kg`,
"#a9e7ff",
new THREE.Vector2(1.1, 0.275)
);
massLabel.sprite.position.set(0, 0.02, 0.69);
massGroup.add(massLabel.sprite);
// ------------------------------------------------------------
// Spring geometry
// ------------------------------------------------------------
class HelixCurve extends THREE.Curve {
constructor(startX, endX, turns, radius, y) {
super();
this.startX = startX;
this.endX = endX;
this.turns = turns;
this.radius = radius;
this.y = y;
}
getPoint(t, target = new THREE.Vector3()) {
const angle = t * this.turns * Math.PI * 2;
// Taper the first and final half-turn so the coil joins its
// anchor and the mass without a visible gap.
const taper = Math.min(1, t * 14, (1 - t) * 14);
const r = this.radius * taper;
target.set(
THREE.MathUtils.lerp(this.startX, this.endX, t),
this.y + Math.cos(angle) * r,
Math.sin(angle) * r
);
return target;
}
}
const springMaterial = standardMaterial(0xd7e7f1, {
metalness: 0.78,
roughness: 0.25,
emissive: 0x152a38,
emissiveIntensity: 0.28
});
function updateSpring() {
const springEnd = massGroup.position.x - MASS_HALF_WIDTH;
if (springMesh) {
scene.remove(springMesh);
springMesh.geometry.dispose();
}
const curve = new HelixCurve(
SPRING_START,
springEnd,
9,
0.145,
SPRING_Y
);
springMesh = new THREE.Mesh(
new THREE.TubeGeometry(curve, 112, 0.037, 5, false),
springMaterial
);
springMesh.castShadow = true;
springMesh.receiveShadow = true;
scene.add(springMesh);
}
// ------------------------------------------------------------
// Equilibrium guide and displacement markers
// ------------------------------------------------------------
const equilibriumLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(REST_X, -1.02, 0.12),
new THREE.Vector3(REST_X, 1.55, 0.12)
]),
new THREE.LineDashedMaterial({
color: 0x75efbd,
dashSize: 0.08,
gapSize: 0.055,
transparent: true,
opacity: 0.72
})
);
equilibriumLine.computeLineDistances();
scene.add(equilibriumLine);
const equilibriumDiamond = new THREE.Mesh(
new THREE.OctahedronGeometry(0.09),
new THREE.MeshStandardMaterial({
color: 0x75efbd,
emissive: 0x163e31,
emissiveIntensity: 0.7,
flatShading: true
})
);
equilibriumDiamond.position.set(REST_X, 1.22, 0.12);
scene.add(equilibriumDiamond);
const markerMaterial = standardMaterial(0x6e91aa, {
metalness: 0.4,
roughness: 0.45
});
const equilibriumMarkerMaterial = standardMaterial(0x75efbd, {
emissive: 0x153d30,
emissiveIntensity: 0.5
});
const markerValues = [-0.4, -0.2, 0, 0.2, 0.4];
for (const value of markerValues) {
const worldX = REST_X + value * WORLD_SCALE;
const isEquilibrium = Math.abs(value) < 0.0001;
const tickBottom = isEquilibrium ? -1.07 : -1.03;
const tickTop = isEquilibrium ? -0.82 : -0.90;
addCylinderBetween(
scene,
new THREE.Vector3(worldX, tickBottom, 0.34),
new THREE.Vector3(worldX, tickTop, 0.34),
isEquilibrium ? 0.024 : 0.014,
isEquilibrium ? equilibriumMarkerMaterial : markerMaterial,
6
);
const text =
value === 0
? "0"
: `${value > 0 ? "+" : "−"}${Math.abs(value).toFixed(2)} m`;
const label = createLabel(
text,
isEquilibrium ? "#75efbd" : "#b6cede",
isEquilibrium
? new THREE.Vector2(0.48, 0.16)
: new THREE.Vector2(0.68, 0.17)
);
label.sprite.position.set(worldX, -1.17, 0.34);
scene.add(label.sprite);
}
const rangeBadge = createLabel(
"HOOKE RANGE |x| ≤ 0.40 m",
"#75efbd",
new THREE.Vector2(2.15, 0.40)
);
rangeBadge.sprite.position.set(-2.15, 1.67, 0);
scene.add(rangeBadge.sprite);
// ------------------------------------------------------------
// Vector arrows
// ------------------------------------------------------------
const displacementArrow = new THREE.ArrowHelper(
new THREE.Vector3(1, 0, 0),
new THREE.Vector3(REST_X, 1.22, 0),
1,
0x43d9ff,
0.16,
0.08
);
const forceArrow = new THREE.ArrowHelper(
new THREE.Vector3(-1, 0, 0),
new THREE.Vector3(REST_X, 0.84, 0),
1,
0xff865f,
0.16,
0.08
);
for (const arrow of [displacementArrow, forceArrow]) {
arrow.line.material.depthTest = false;
arrow.cone.material.depthTest = false;
arrow.line.renderOrder = 20;
arrow.cone.renderOrder = 20;
scene.add(arrow);
}
const displacementLabel = createLabel(
"x = +0.00 m",
"#43d9ff",
new THREE.Vector2(1.25, 0.31)
);
scene.add(displacementLabel.sprite);
const forceLabel = createLabel(
"Fᵣ = 0.00 N",
"#ff865f",
new THREE.Vector2(1.25, 0.31)
);
scene.add(forceLabel.sprite);
// ------------------------------------------------------------
// Physics and UI update
// ------------------------------------------------------------
function signed(value, decimals = 2) {
const sign = value > 0 ? "+" : value < 0 ? "−" : "";
return `${sign}${Math.abs(value).toFixed(decimals)}`;
}
function setDisplacement(value) {
// The slider and drag interaction are intentionally constrained
// to the stated Hooke-law range.
displacement = THREE.MathUtils.clamp(value, MIN_X, MAX_X);
const massX = REST_X + displacement * WORLD_SCALE;
massGroup.position.x = massX;
const force = -K * displacement;
const sign = Math.sign(displacement);
const displacementLength = Math.abs(displacement) * WORLD_SCALE;
const forceLength = Math.min(1.30, Math.abs(force) * 0.27);
slider.value = displacement.toFixed(2);
xOutput.textContent = `${signed(displacement)} m`;
forceOutput.textContent = `${signed(force)} N`;
displacementLabel.setText(`x = ${signed(displacement)} m`);
forceLabel.setText(`Fᵣ = ${signed(force)} N`);
if (Math.abs(displacement) <= 0.0001) {
directionOutput.textContent =
"Zero displacement at equilibrium; the restoring force is zero.";
} else if (displacement > 0) {
directionOutput.textContent =
"Mass is right of equilibrium; the restoring force points left.";
} else {
directionOutput.textContent =
"Mass is left of equilibrium; the restoring force points right.";
}
const insideRange =
displacement >= MIN_X - 1e-6 &&
displacement <= MAX_X + 1e-6;
statusOutput.textContent = insideRange
? "In Hooke range"
: "Outside Hooke range";
statusOutput.style.color = insideRange ? "#75efbd" : "#ff865f";
// Displacement vector: equilibrium toward the mass.
displacementArrow.visible = Math.abs(displacement) > 0.005;
displacementArrow.position.set(REST_X, 1.22, 0);
displacementArrow.setDirection(
new THREE.Vector3(sign || 1, 0, 0)
);
displacementArrow.setLength(
Math.max(0.10, displacementLength),
0.16,
0.08
);
displacementLabel.sprite.visible = displacementArrow.visible;
displacementLabel.sprite.position.set(
REST_X + sign * displacementLength * 0.5,
1.43,
0
);
// Restoring force: always opposite to displacement.
forceArrow.visible = Math.abs(force) > 0.02;
forceArrow.position.set(massX, 0.84, 0);
forceArrow.setDirection(
new THREE.Vector3(-sign || 1, 0, 0)
);
forceArrow.setLength(
Math.max(0.10, forceLength),
0.16,
0.08
);
forceLabel.sprite.visible = forceArrow.visible;
forceLabel.sprite.position.set(
massX - sign * forceLength * 0.5,
0.84,
0
);
updateSpring();
}
slider.addEventListener("input", () => {
setDisplacement(Number(slider.value));
});
document.querySelectorAll("[data-displacement]").forEach((button) => {
button.addEventListener("click", () => {
setDisplacement(Number(button.dataset.displacement));
});
});
// ------------------------------------------------------------
// Direct mass dragging
// ------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const dragPoint = new THREE.Vector3();
let draggingMass = false;
let orbiting = false;
let dragOffset = 0;
let lastPointerX = 0;
let lastPointerY = 0;
function setPointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
setPointerFromEvent(event);
scene.updateMatrixWorld(true);
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObject(massBody, false);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
if (hits.length > 0) {
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
draggingMass = true;
dragOffset =
displacement -
(dragPoint.x - REST_X) / WORLD_SCALE;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
}
} else {
orbiting = true;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "move";
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (draggingMass) {
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
const draggedDisplacement =
(dragPoint.x - REST_X) / WORLD_SCALE + dragOffset;
setDisplacement(draggedDisplacement);
}
} else if (orbiting) {
const dx = event.clientX - lastPointerX;
const dy = event.clientY - lastPointerY;
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - dy * 0.005,
0.55,
1.45
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
}
});
function endPointerInteraction(event) {
draggingMass = false;
orbiting = false;
renderer.domElement.style.cursor = "default";
if (
event &&
renderer.domElement.hasPointerCapture(event.pointerId)
) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endPointerInteraction);
renderer.domElement.addEventListener("pointercancel", endPointerInteraction);
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
// Direct wheel zoom, implemented without camera-control addons.
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
4.6,
12.0
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraRadius = 8.0;
cameraTheta = 0.10;
cameraPhi = 1.25;
cameraTarget.set(-1.10, -0.05, 0);
updateCamera();
});
// ------------------------------------------------------------
// Resize and initial state
// ------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(
Math.min(window.devicePixelRatio, 2)
);
renderer.setSize(
window.innerWidth,
window.innerHeight
);
});
setDisplacement(0);
renderer.setAnimationLoop(() => {
renderer.render(scene, camera);
});
</script>
</body>
</html>
```