Prompt specification
Build or customize the Three.js 3D scene "Balanced playground design game" 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: Balanced playground design game
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/balanced-playground-design-game-x0368
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Create a tabletop seesaw puzzle with movable seats and weight blocks; users achieve a target angle using an explicit lever equation and can reset every arrangement.
Working Three.js Starter (balanced-playground-design-game-x0368):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Lever Lab — Tabletop Seesaw Puzzle</title>
<style>
:root {
--ink: #18313a;
--muted: #61747b;
--paper: rgba(255, 252, 245, 0.92);
--line: rgba(24, 49, 58, 0.13);
--accent: #e76f51;
--accent-dark: #b94730;
--teal: #287f7b;
--gold: #e7b84b;
--success: #23836f;
--shadow: 0 18px 45px rgba(46, 40, 28, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #e9e3d8;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#stage,
#stage canvas {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
}
.ui {
position: absolute;
inset: 0;
pointer-events: none;
}
.panel {
pointer-events: auto;
border: 1px solid rgba(255, 255, 255, 0.72);
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.brand {
position: absolute;
top: 22px;
left: 22px;
display: flex;
align-items: center;
gap: 12px;
padding: 12px 16px;
border-radius: 16px;
}
.brand-mark {
width: 38px;
height: 38px;
display: grid;
place-items: center;
border-radius: 12px;
background: var(--ink);
color: #fff8e9;
font-size: 23px;
transform: rotate(-5deg);
}
.brand h1 {
margin: 0;
font-size: 16px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.brand p {
margin: 2px 0 0;
color: var(--muted);
font-size: 12px;
}
.objective {
position: absolute;
top: 102px;
left: 22px;
width: 270px;
padding: 18px;
border-radius: 20px;
transition: border-color 180ms ease, box-shadow 180ms ease;
}
.objective.solved {
border-color: rgba(35, 131, 111, 0.55);
box-shadow: 0 18px 50px rgba(35, 131, 111, 0.22);
}
.eyebrow {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.objective-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 14px;
margin-top: 10px;
}
.objective-title h2 {
margin: 0;
font-size: 24px;
line-height: 1.05;
}
.objective-title p {
margin: 7px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.4;
}
.gauge {
position: relative;
width: 82px;
height: 82px;
flex: 0 0 auto;
border: 1px solid rgba(24, 49, 58, 0.13);
border-radius: 50%;
background:
radial-gradient(circle at 50% 50%, #fff 0 47%, transparent 48%),
conic-gradient(from 210deg, #e6ded1, #faf7ef, #e6ded1);
box-shadow: inset 0 0 0 7px rgba(255, 255, 255, 0.45);
}
.gauge::after {
content: "";
position: absolute;
left: 50%;
top: 50%;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--ink);
transform: translate(-50%, -50%);
}
.needle,
.target-needle {
position: absolute;
left: 50%;
top: 50%;
height: 3px;
border-radius: 3px;
transform-origin: 0 50%;
pointer-events: none;
}
.needle {
width: 35px;
background: var(--accent);
transform: rotate(0deg);
}
.target-needle {
width: 39px;
height: 2px;
background: var(--teal);
opacity: 0.8;
}
.gauge-label {
position: absolute;
bottom: 5px;
color: var(--muted);
font-size: 8px;
font-weight: 800;
letter-spacing: 0.08em;
}
.gauge-label.left {
left: 7px;
}
.gauge-label.right {
right: 7px;
}
.challenge-row {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 6px;
margin-top: 15px;
}
.challenge-row button {
min-height: 34px;
padding: 7px 5px;
border: 1px solid var(--line);
border-radius: 9px;
background: rgba(255, 255, 255, 0.62);
color: var(--muted);
font: inherit;
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition: 150ms ease;
}
.challenge-row button:hover {
transform: translateY(-1px);
border-color: rgba(24, 49, 58, 0.3);
}
.challenge-row button.active {
background: var(--ink);
border-color: var(--ink);
color: white;
}
.status {
display: flex;
align-items: center;
gap: 9px;
margin-top: 14px;
padding: 10px 11px;
border-radius: 11px;
background: rgba(24, 49, 58, 0.055);
color: var(--muted);
font-size: 12px;
font-weight: 700;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #b3a99b;
box-shadow: 0 0 0 4px rgba(179, 169, 155, 0.16);
}
.solved .status {
color: var(--success);
background: rgba(35, 131, 111, 0.1);
}
.solved .status-dot {
background: var(--success);
box-shadow: 0 0 0 4px rgba(35, 131, 111, 0.16);
}
.tools {
position: absolute;
top: 22px;
right: 22px;
display: flex;
gap: 8px;
padding: 9px;
border-radius: 15px;
}
.tool {
border: 0;
border-radius: 10px;
padding: 10px 13px;
background: rgba(24, 49, 58, 0.07);
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 800;
cursor: pointer;
transition: 150ms ease;
}
.tool:hover {
background: rgba(24, 49, 58, 0.13);
transform: translateY(-1px);
}
.tool.primary {
background: var(--accent);
color: white;
}
.tool.primary:hover {
background: var(--accent-dark);
}
.equation {
position: absolute;
left: 22px;
bottom: 22px;
width: min(390px, calc(100vw - 44px));
padding: 17px 18px 15px;
border-radius: 20px;
}
.equation-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.equation-heading h2 {
margin: 0;
font-size: 14px;
}
.live-badge {
padding: 4px 7px;
border-radius: 6px;
background: rgba(231, 111, 81, 0.12);
color: var(--accent-dark);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.12em;
}
.moment-row {
display: grid;
grid-template-columns: 26px 1fr auto;
gap: 9px;
align-items: center;
min-height: 28px;
border-bottom: 1px dashed var(--line);
font-size: 12px;
}
.moment-side {
display: grid;
place-items: center;
width: 23px;
height: 23px;
border-radius: 7px;
color: white;
font-size: 10px;
font-weight: 900;
}
.moment-side.right {
background: var(--accent);
}
.moment-side.left {
background: var(--teal);
}
.moment-row code {
overflow: hidden;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
.moment-row b {
font-size: 12px;
}
.formula {
display: flex;
justify-content: space-between;
gap: 12px;
margin-top: 10px;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
line-height: 1.5;
}
.formula span {
color: var(--muted);
}
.formula b {
white-space: nowrap;
}
.target-condition {
margin-top: 11px;
padding: 9px 10px;
border-radius: 10px;
background: rgba(40, 127, 123, 0.09);
color: #276d69;
font-size: 11px;
font-weight: 800;
}
.instructions {
position: absolute;
right: 22px;
bottom: 22px;
max-width: 330px;
padding: 12px 15px;
border-radius: 14px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
text-align: right;
}
.instructions strong {
color: var(--ink);
}
.hint {
position: absolute;
left: 50%;
bottom: 22px;
width: min(440px, calc(100vw - 44px));
padding: 14px 17px;
border-radius: 15px;
transform: translate(-50%, 20px);
opacity: 0;
visibility: hidden;
transition: 180ms ease;
font-size: 12px;
line-height: 1.55;
}
.hint.visible {
transform: translate(-50%, 0);
opacity: 1;
visibility: visible;
}
.hint strong {
display: block;
margin-bottom: 4px;
color: var(--accent-dark);
}
.toast {
position: absolute;
left: 50%;
top: 24px;
padding: 11px 16px;
border-radius: 12px;
background: var(--ink);
color: white;
box-shadow: var(--shadow);
transform: translate(-50%, -20px);
opacity: 0;
visibility: hidden;
font-size: 12px;
font-weight: 800;
transition: 180ms ease;
}
.toast.show {
transform: translate(-50%, 0);
opacity: 1;
visibility: visible;
}
@media (max-width: 900px) {
.instructions {
display: none;
}
.equation {
bottom: 16px;
left: 16px;
width: min(360px, calc(100vw - 32px));
}
.objective {
top: 96px;
left: 16px;
width: 245px;
}
.brand {
top: 16px;
left: 16px;
}
.tools {
top: 16px;
right: 16px;
}
}
@media (max-width: 620px) {
.brand p,
.tool span {
display: none;
}
.brand {
padding: 9px 11px;
}
.brand-mark {
width: 32px;
height: 32px;
}
.objective {
top: 82px;
width: 205px;
padding: 13px;
}
.objective-title h2 {
font-size: 19px;
}
.gauge {
width: 65px;
height: 65px;
}
.equation {
padding: 13px;
}
.formula {
font-size: 9px;
}
.hint {
bottom: 16px;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<div class="ui">
<header class="brand panel">
<div class="brand-mark">⚖</div>
<div>
<h1>Lever Lab</h1>
<p>Tabletop seesaw puzzle</p>
</div>
</header>
<section id="objective" class="objective panel">
<div class="eyebrow">Current challenge</div>
<div class="objective-title">
<div>
<h2 id="targetTitle">+8° right</h2>
<p>Balance the moments to reach the marked angle.</p>
</div>
<div class="gauge" aria-label="Angle gauge">
<div id="targetNeedle" class="target-needle"></div>
<div id="needle" class="needle"></div>
<span class="gauge-label left">L</span>
<span class="gauge-label right">R</span>
</div>
</div>
<div class="challenge-row" aria-label="Choose a challenge">
<button type="button" data-challenge="right" class="active">+8° right</button>
<button type="button" data-challenge="left">−8° left</button>
<button type="button" data-challenge="level">0° level</button>
</div>
<div class="status">
<span class="status-dot"></span>
<span id="statusText">Adjust the lever moments</span>
</div>
</section>
<nav class="tools panel" aria-label="Puzzle controls">
<button id="resetButton" class="tool primary" type="button">
↺ Reset arrangement
</button>
<button id="cameraButton" class="tool" type="button">
◎ <span>Camera</span>
</button>
<button id="hintButton" class="tool" type="button">
? <span>Hint</span>
</button>
</nav>
<section class="equation panel">
<div class="equation-heading">
<h2>Live lever equation</h2>
<span class="live-badge">LIVE</span>
</div>
<div class="moment-row">
<span class="moment-side right">R</span>
<code id="rightTerms">—</code>
<b id="rightValue">0.00 kg·m</b>
</div>
<div class="moment-row">
<span class="moment-side left">L</span>
<code id="leftTerms">—</code>
<b id="leftValue">0.00 kg·m</b>
</div>
<div class="formula">
<span>M<sub>net</sub> = Σm<sub>i</sub>gr<sub>i</sub> = g(M<sub>R</sub> − M<sub>L</sub>)</span>
<b id="netValue">0.00 N·m</b>
</div>
<div class="formula">
<span>θ = clamp[8° × (M<sub>net</sub>/g)/(1 kg·m), −24°, 24°]</span>
<b id="angleValue">0.0°</b>
</div>
<div id="targetCondition" class="target-condition">
Target condition: M<sub>R</sub> − M<sub>L</sub> = +1.00 kg·m
</div>
</section>
<div class="instructions panel">
<strong>Drag seats</strong> along the beam.<br />
<strong>Drag blocks</strong> between seats.<br />
Drag empty space to orbit · Scroll to zoom · R to reset
</div>
<div id="hint" class="hint panel">
<strong>Hint</strong>
<span id="hintText"></span>
</div>
<div id="toast" class="toast"></div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Constants and state
// -------------------------------------------------------------------------
const $ = (id) => document.getElementById(id);
const G = 9.81;
const ANGLE_PER_KG_M = 8;
const MAX_ANGLE = 24;
const SLOT_POSITIONS = [-0.30, 0.30];
const challenges = {
right: {
target: 8,
title: "+8° right",
hint:
"Place the 1 kg block on the left seat at −4 m. Place the 2 kg and 3 kg blocks on the right seat at +1 m. Then Mᵣ = 5 and Mₗ = 4 kg·m."
},
left: {
target: -8,
title: "−8° left",
hint:
"Place the 2 kg and 3 kg blocks on the left seat at −1 m. Place the 1 kg block on the right seat at +4 m. Then Mᵣ = 4 and Mₗ = 5 kg·m."
},
level: {
target: 0,
title: "0° level",
hint:
"Place the 3 kg block on the left seat at −1 m. Place the 1 kg and 2 kg blocks on the right seat at +1 m. Both moments will be 3 kg·m."
}
};
let challengeKey = "right";
let targetAngle = challenges.right.target;
let desiredAngle = 0;
let currentAngle = 0;
let wasSuccessful = false;
let dragState = null;
let orbitState = null;
let toastTimer = 0;
const defaultSeatPositions = [-2, 2];
const defaultBlockLayout = [
{ seat: 0, slot: 0 },
{ seat: 1, slot: 0 },
{ seat: 0, slot: 1 }
];
// -------------------------------------------------------------------------
// Renderer, scene, camera, lights
// -------------------------------------------------------------------------
const stage = $("stage");
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xe9e3d8);
scene.fog = new THREE.Fog(0xe9e3d8, 24, 48);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 0.65, 0);
const cameraState = {
theta: 0.64,
phi: 0.96,
radius: 14.5,
targetTheta: 0.64,
targetPhi: 0.96,
targetRadius: 14.5
};
const hemisphere = new THREE.HemisphereLight(0xfff8e9, 0x6d6355, 2.1);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xfff1d6, 3.2);
keyLight.position.set(7, 11, 8);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -11;
keyLight.shadow.camera.right = 11;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const fillLight = new THREE.DirectionalLight(0x91b7d9, 0.85);
fillLight.position.set(-8, 5, -7);
scene.add(fillLight);
// -------------------------------------------------------------------------
// Materials and geometry helpers
// -------------------------------------------------------------------------
const material = (color, options = {}) =>
new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0,
flatShading: true,
...options
});
const tableWood = material(0x9b6846);
const tableEdge = material(0x72462f);
const legWood = material(0x69402c);
const beamWood = material(0xd89a55);
const beamEdge = material(0xb86f36);
const rulerInk = material(0x5a3b2d);
const brass = material(0xe4b54b, { metalness: 0.38, roughness: 0.5 });
const fulcrumMaterial = material(0x386e70);
const floorMaterial = material(0xd9d2c6);
function makeBox(size, mat, position, parent = scene) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(...size), mat);
mesh.position.set(...position);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function makeTriangularPrism(width, height, depth) {
const w = width / 2;
const d = depth / 2;
const vertices = new Float32Array([
-w, 0, d,
w, 0, d,
0, height, d,
-w, 0, -d,
w, 0, -d,
0, height, -d
]);
const indices = [
0, 1, 2,
3, 5, 4,
0, 3, 4,
0, 4, 1,
0, 2, 5,
0, 5, 3,
1, 4, 5,
1, 5, 2
];
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(vertices, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
return geometry;
}
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.arcTo(x + width, y, x + width, y + height, r);
ctx.arcTo(x + width, y + height, x, y + height, r);
ctx.arcTo(x, y + height, x, y, r);
ctx.arcTo(x, y, x + width, y, r);
ctx.closePath();
}
function makeLabel(
initialText,
{
width = 512,
height = 160,
background = "#203840",
foreground = "#ffffff",
font = "800 52px system-ui, sans-serif",
scale = [1.2, 0.38]
} = {}
) {
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const context = canvas.getContext("2d");
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
const sprite = new THREE.Sprite(
new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
})
);
sprite.scale.set(scale[0], scale[1], 1);
sprite.renderOrder = 8;
function set(text) {
context.clearRect(0, 0, width, height);
roundedRect(context, 8, 8, width - 16, height - 16, 28);
context.fillStyle = background;
context.fill();
context.fillStyle = foreground;
context.font = font;
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, width / 2, height / 2 + 2);
texture.needsUpdate = true;
}
set(initialText);
return { sprite, set };
}
// -------------------------------------------------------------------------
// Tabletop and room
// -------------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(80, 80),
floorMaterial
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -4.12;
floor.receiveShadow = true;
scene.add(floor);
makeBox([15.4, 0.56, 9.2], tableWood, [0, -0.28, 0]);
makeBox([15.55, 0.16, 9.35], tableEdge, [0, -0.59, 0]);
for (const x of [-6.45, 6.45]) {
for (const z of [-3.55, 3.55]) {
makeBox([0.58, 4.05, 0.58], legWood, [x, -2.08, z]);
}
}
const grooveMaterial = material(0x75472f);
for (let x = -6.5; x <= 6.5; x += 1.3) {
makeBox([0.025, 0.015, 8.95], grooveMaterial, [x, 0.008, 0]);
}
// -------------------------------------------------------------------------
// Seesaw and fulcrum
// -------------------------------------------------------------------------
const fulcrum = new THREE.Mesh(
makeTriangularPrism(1.75, 1.78, 1.05),
fulcrumMaterial
);
fulcrum.position.y = 0.025;
fulcrum.castShadow = true;
fulcrum.receiveShadow = true;
scene.add(fulcrum);
const axle = new THREE.Mesh(
new THREE.CylinderGeometry(0.18, 0.18, 1.58, 16),
brass
);
axle.rotation.x = Math.PI / 2;
axle.position.y = 1.82;
axle.castShadow = true;
scene.add(axle);
const beamGroup = new THREE.Group();
beamGroup.position.y = 1.82;
scene.add(beamGroup);
makeBox([11.15, 0.32, 1.3], beamWood, [0, 0, 0], beamGroup);
makeBox([0.22, 0.36, 1.36], beamEdge, [-5.47, 0, 0], beamGroup);
makeBox([0.22, 0.36, 1.36], beamEdge, [5.47, 0, 0], beamGroup);
for (let x = -4; x <= 4; x++) {
const major = x === 0 || x === -4 || x === 4;
makeBox(
[major ? 0.055 : 0.035, major ? 0.20 : 0.13, 0.025],
rulerInk,
[x, 0.07, 0.663],
beamGroup
);
}
const pivotCap = new THREE.Mesh(
new THREE.CylinderGeometry(0.27, 0.27, 0.17, 16),
brass
);
pivotCap.rotation.x = Math.PI / 2;
pivotCap.position.set(0, 0, 0.73);
pivotCap.castShadow = true;
beamGroup.add(pivotCap);
// -------------------------------------------------------------------------
// Movable seats
// -------------------------------------------------------------------------
const seats = [];
function createSeat(index, name, color) {
const group = new THREE.Group();
group.userData = { type: "seat", index };
beamGroup.add(group);
const seatMaterial = material(color);
const darkMaterial = material(0x244b4d);
const padMaterial = material(color, {
emissive: 0xffaa55,
emissiveIntensity: 0
});
makeBox([1.10, 0.13, 0.13], darkMaterial, [0, 0.235, -0.37], group);
makeBox([1.10, 0.13, 0.13], darkMaterial, [0, 0.235, 0.37], group);
makeBox([0.13, 0.28, 0.13], darkMaterial, [-0.37, 0.31, 0], group);
makeBox([0.13, 0.28, 0.13], darkMaterial, [0.37, 0.31, 0], group);
const pad = makeBox([0.98, 0.18, 0.93], padMaterial, [0, 0.47, 0], group);
makeBox([0.98, 0.58, 0.13], seatMaterial, [0, 0.80, -0.42], group);
const label = makeLabel("SEAT", {
background: "#203840",
foreground: "#ffffff",
font: "800 49px system-ui, sans-serif",
scale: [1.18, 0.37]
});
label.sprite.position.set(0, 0.56, 0.55);
group.add(label.sprite);
const seat = {
index,
name,
group,
pad,
padMaterial,
label,
x: defaultSeatPositions[index]
};
group.position.x = seat.x;
seats.push(seat);
}
createSeat(0, "SEAT A", 0x2c8b84);
createSeat(1, "SEAT B", 0xd66c4e);
function formatPosition(value) {
if (value === 0) return "0 m";
return `${value > 0 ? "+" : "−"}${Math.abs(value)} m`;
}
function updateSeatLabel(seat) {
seat.label.set(`${seat.name} · ${formatPosition(seat.x)}`);
}
seats.forEach(updateSeatLabel);
// -------------------------------------------------------------------------
// Weight blocks
// -------------------------------------------------------------------------
const blocks = [];
function createBlock(id, mass, color, seatIndex, slotIndex) {
const group = new THREE.Group();
group.userData = { type: "block", id };
const blockMaterial = material(color);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x493b35,
transparent: true,
opacity: 0.7
});
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.58, 0.58, 0.58),
blockMaterial
);
cube.castShadow = true;
cube.receiveShadow = true;
group.add(cube);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(cube.geometry),
edgeMaterial
);
edges.renderOrder = 2;
group.add(edges);
makeBox(
[0.22, 0.07, 0.22],
material(new THREE.Color(color).multiplyScalar(0.78)),
[0, 0.325, 0],
group
);
const label = makeLabel(`${mass} kg`, {
background: "#fffaf0",
foreground: "#263940",
font: "900 52px system-ui, sans-serif",
scale: [0.73, 0.37]
});
label.sprite.position.set(0, 0.72, 0);
group.add(label.sprite);
blocks.push({
id,
mass,
group,
seat: seatIndex,
slot: slotIndex
});
}
createBlock("coral", 1, 0xef6b59, 0, 0);
createBlock("blue", 2, 0x5577e6, 1, 0);
createBlock("yellow", 3, 0xf0c24f, 0, 1);
function layoutBlocks() {
for (const block of blocks) {
const seat = seats[block.seat];
if (!seat) continue;
if (block.group.parent !== seat.group) {
seat.group.attach(block.group);
}
block.group.position.set(
0,
0.87,
SLOT_POSITIONS[block.slot] ?? SLOT_POSITIONS[0]
);
block.group.rotation.set(0, 0, 0);
}
}
layoutBlocks();
// -------------------------------------------------------------------------
// Lever calculations and UI
// -------------------------------------------------------------------------
function calculateMoments() {
const right = [];
const left = [];
let rightMoment = 0;
let leftMoment = 0;
for (const block of blocks) {
const arm = seats[block.seat].x;
if (arm > 0) {
rightMoment += block.mass * arm;
right.push({ block, arm });
} else if (arm < 0) {
leftMoment += block.mass * Math.abs(arm);
left.push({ block, arm: Math.abs(arm) });
}
}
const delta = rightMoment - leftMoment;
const netNewtonMeters = delta * G;
const angle = THREE.MathUtils.clamp(
delta * ANGLE_PER_KG_M,
-MAX_ANGLE,
MAX_ANGLE
);
return { right, left, rightMoment, leftMoment, delta, netNewtonMeters, angle };
}
function signedNumber(value, decimals = 2) {
if (Math.abs(value) < 0.0001) return (0).toFixed(decimals);
return `${value > 0 ? "+" : "−"}${Math.abs(value).toFixed(decimals)}`;
}
function signedAngle(value) {
if (Math.abs(value) < 0.05) return "0.0°";
return `${value > 0 ? "+" : "−"}${Math.abs(value).toFixed(1)}°`;
}
function updateEquation() {
const result = calculateMoments();
desiredAngle = result.angle;
$("rightTerms").textContent =
result.right.length
? result.right.map(({ block, arm }) => `${block.mass}×${arm}`).join(" + ")
: "no right-side load";
$("leftTerms").textContent =
result.left.length
? result.left.map(({ block, arm }) => `${block.mass}×${arm}`).join(" + ")
: "no left-side load";
$("rightValue").textContent = `${result.rightMoment.toFixed(2)} kg·m`;
$("leftValue").textContent = `${result.leftMoment.toFixed(2)} kg·m`;
$("netValue").textContent = `${signedNumber(result.netNewtonMeters)} N·m`;
$("angleValue").textContent = signedAngle(result.angle);
const targetDelta = targetAngle / ANGLE_PER_KG_M;
$("targetCondition").innerHTML =
`Target condition: M<sub>R</sub> − M<sub>L</sub> = ` +
`${signedNumber(targetDelta)} kg·m`;
const successful = Math.abs(result.angle - targetAngle) < 0.02;
$("objective").classList.toggle("solved", successful);
if (successful) {
$("statusText").textContent = "Target reached — moments balanced";
} else {
const difference = targetDelta - result.delta;
$("statusText").textContent =
`${difference > 0 ? "Increase" : "Decrease"} right-side moment by ` +
`${Math.abs(difference).toFixed(2)} kg·m`;
}
return successful;
}
function updateChallengeUI() {
$("targetTitle").textContent = challenges[challengeKey].title;
$("targetNeedle").style.transform = `rotate(${targetAngle}deg)`;
document.querySelectorAll("[data-challenge]").forEach((button) => {
const active = button.dataset.challenge === challengeKey;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
$("hintText").textContent = challenges[challengeKey].hint;
}
function showToast(message) {
const toast = $("toast");
toast.textContent = message;
toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => toast.classList.remove("show"), 2200);
}
// -------------------------------------------------------------------------
// Reset and challenge selection
// -------------------------------------------------------------------------
const confettiParticles = [];
const confettiGeometry = new THREE.BoxGeometry(0.10, 0.10, 0.10);
const confettiMaterials = [
material(0xef6b59),
material(0x5577e6),
material(0xf0c24f),
material(0x2c8b84)
];
function clearConfetti() {
for (const particle of confettiParticles) {
scene.remove(particle.mesh);
}
confettiParticles.length = 0;
}
function resetArrangement(showMessage = true) {
seats.forEach((seat, index) => {
seat.x = defaultSeatPositions[index];
seat.group.position.x = seat.x;
updateSeatLabel(seat);
});
blocks.forEach((block, index) => {
block.seat = defaultBlockLayout[index].seat;
block.slot = defaultBlockLayout[index].slot;
});
layoutBlocks();
clearConfetti();
wasSuccessful = false;
const successful = updateEquation();
if (!successful) {
// Let the beam settle from its current pose toward the reset pose.
desiredAngle = calculateMoments().angle;
}
if (showMessage) {
showToast("Seats and weight blocks reset");
}
}
function setChallenge(key) {
challengeKey = key;
targetAngle = challenges[key].target;
updateChallengeUI();
resetArrangement(false);
showToast(`Challenge changed: ${challenges[key].title}`);
}
document.querySelectorAll("[data-challenge]").forEach((button) => {
button.addEventListener("click", () => {
setChallenge(button.dataset.challenge);
});
});
$("resetButton").addEventListener("click", () => resetArrangement(true));
$("hintButton").addEventListener("click", () => {
$("hint").classList.toggle("visible");
});
// -------------------------------------------------------------------------
// Custom camera controls — no external controls addon
// -------------------------------------------------------------------------
function resetCamera() {
cameraState.targetTheta = 0.64;
cameraState.targetPhi = 0.96;
cameraState.targetRadius = 14.5;
showToast("Camera reset");
}
$("cameraButton").addEventListener("click", resetCamera);
function updateCamera(dt) {
const easing = 1 - Math.exp(-10 * dt);
cameraState.theta += (cameraState.targetTheta - cameraState.theta) * easing;
cameraState.phi += (cameraState.targetPhi - cameraState.phi) * easing;
cameraState.radius += (cameraState.targetRadius - cameraState.radius) * easing;
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraTarget.x +
cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraTarget.y + cameraState.radius * Math.cos(cameraState.phi),
cameraTarget.z +
cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraTarget);
}
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.targetRadius = THREE.MathUtils.clamp(
cameraState.targetRadius + event.deltaY * 0.012,
9,
23
);
},
{ passive: false }
);
// -------------------------------------------------------------------------
// Picking and dragging
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
raycaster.params.Line.threshold = 0.06;
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane();
const planePoint = new THREE.Vector3();
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;
raycaster.setFromCamera(pointer, camera);
}
function interactiveAncestor(object) {
let current = object;
while (current && current !== scene) {
if (current.userData?.type) return current;
current = current.parent;
}
return null;
}
function pick(event) {
setPointerFromEvent(event);
const roots = [...seats.map((seat) => seat.group), ...blocks.map((block) => block.group)];
const intersections = raycaster.intersectObjects(roots, true);
for (const intersection of intersections) {
const interactive = interactiveAncestor(intersection.object);
if (interactive) return interactive;
}
return null;
}
function updateDragPlane() {
beamGroup.updateWorldMatrix(true, false);
const xAxis = new THREE.Vector3(1, 0, 0).applyQuaternion(
beamGroup.getWorldQuaternion(new THREE.Quaternion())
);
const viewDirection = camera.getWorldDirection(new THREE.Vector3());
const normal = viewDirection.clone();
normal.addScaledVector(xAxis, -normal.dot(xAxis));
if (normal.lengthSq() < 0.0001) {
normal.set(0, 0, 1);
} else {
normal.normalize();
}
const origin = beamGroup.getWorldPosition(new THREE.Vector3());
dragPlane.setFromNormalAndCoplanarPoint(normal, origin);
}
function pointerToBeam(event) {
setPointerFromEvent(event);
updateDragPlane();
if (!raycaster.ray.intersectPlane(dragPlane, planePoint)) {
return null;
}
beamGroup.updateWorldMatrix(true, false);
return beamGroup.worldToLocal(planePoint.clone());
}
function highlightSeats(activeIndex = -1) {
seats.forEach((seat, index) => {
seat.padMaterial.emissiveIntensity = index === activeIndex ? 0.42 : 0;
});
}
function startSeatDrag(seat, event) {
const local = pointerToBeam(event);
if (!local) return;
dragState = {
type: "seat",
seat,
startX: seat.x,
offsetX: local.x - seat.group.position.x
};
renderer.domElement.style.cursor = "grabbing";
}
function startBlockDrag(block, event) {
const local = pointerToBeam(event);
if (!local) return;
beamGroup.updateWorldMatrix(true, false);
beamGroup.attach(block.group);
dragState = {
type: "block",
block,
oldSeat: block.seat,
oldSlot: block.slot,
offsetX: block.group.position.x - local.x
};
block.group.position.set(
THREE.MathUtils.clamp(local.x + dragState.offsetX, -5.25, 5.25),
1.2,
0
);
renderer.domElement.style.cursor = "grabbing";
}
function moveSeatDrag(event) {
const local = pointerToBeam(event);
if (!local) return;
const candidate = THREE.MathUtils.clamp(
Math.round(local.x - dragState.offsetX),
-4,
4
);
const other = seats.find((seat) => seat !== dragState.seat);
// Swapping the two seats makes crossing the beam convenient.
if (other && candidate === other.x) {
other.x = dragState.startX;
dragState.seat.x = candidate;
} else {
dragState.seat.x = candidate;
}
other.group.position.x = other.x;
dragState.seat.group.position.x = dragState.seat.x;
updateSeatLabel(other);
updateSeatLabel(dragState.seat);
layoutBlocks();
updateEquation();
}
function moveBlockDrag(event) {
const local = pointerToBeam(event);
if (!local) return;
dragState.block.group.position.set(
THREE.MathUtils.clamp(local.x + dragState.offsetX, -5.25, 5.25),
1.2,
0
);
let nearest = -1;
let nearestDistance = Infinity;
seats.forEach((seat, index) => {
const distance = Math.abs(seat.x - dragState.block.group.position.x);
if (distance < nearestDistance) {
nearestDistance = distance;
nearest = index;
}
});
highlightSeats(nearestDistance <= 1.45 ? nearest : -1);
}
function finishBlockDrag(cancel = false) {
const block = dragState.block;
let targetSeat = dragState.oldSeat;
let targetSlot = dragState.oldSlot;
if (!cancel) {
let nearest = -1;
let nearestDistance = Infinity;
seats.forEach((seat, index) => {
const distance = Math.abs(seat.x - block.group.position.x);
if (distance < nearestDistance) {
nearestDistance = distance;
nearest = index;
}
});
if (nearest >= 0 && nearestDistance <= 1.45) {
const occupied = new Set(
blocks
.filter((other) => other !== block && other.seat === nearest)
.map((other) => other.slot)
);
let freeSlot = null;
if (
nearest === dragState.oldSeat &&
!occupied.has(dragState.oldSlot)
) {
freeSlot = dragState.oldSlot;
} else {
freeSlot = [0, 1].find((slot) => !occupied.has(slot));
}
if (freeSlot !== null) {
targetSeat = nearest;
targetSlot = freeSlot;
} else {
showToast("That seat is full — move another block first");
}
}
}
block.seat = targetSeat;
block.slot = targetSlot;
layoutBlocks();
highlightSeats(-1);
updateEquation();
}
function finishDrag(cancel = false) {
if (!dragState) return;
if (dragState.type === "block") {
finishBlockDrag(cancel);
} else if (cancel) {
dragState.seat.x = dragState.startX;
dragState.seat.group.position.x = dragState.seat.x;
updateSeatLabel(dragState.seat);
layoutBlocks();
updateEquation();
}
dragState = null;
renderer.domElement.style.cursor = "grab";
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
const hit = event.button === 0 ? pick(event) : null;
if (hit) {
event.preventDefault();
renderer.domElement.setPointerCapture(event.pointerId);
if (hit.userData.type === "seat") {
const seat = seats[hit.userData.index];
startSeatDrag(seat, event);
} else {
const block = blocks.find((item) => item.id === hit.userData.id);
startBlockDrag(block, event);
}
} else {
event.preventDefault();
renderer.domElement.setPointerCapture(event.pointerId);
orbitState = {
x: event.clientX,
y: event.clientY
};
renderer.domElement.style.cursor = "grabbing";
}
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (dragState) {
if (dragState.type === "seat") moveSeatDrag(event);
else moveBlockDrag(event);
return;
}
if (orbitState) {
const dx = event.clientX - orbitState.x;
const dy = event.clientY - orbitState.y;
cameraState.targetTheta -= dx * 0.006;
cameraState.targetPhi = THREE.MathUtils.clamp(
cameraState.targetPhi - dy * 0.005,
0.38,
1.42
);
orbitState.x = event.clientX;
orbitState.y = event.clientY;
return;
}
renderer.domElement.style.cursor = pick(event) ? "grab" : "default";
});
renderer.domElement.addEventListener("pointerup", (event) => {
finishDrag(false);
orbitState = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
renderer.domElement.style.cursor = "default";
});
renderer.domElement.addEventListener("pointercancel", (event) => {
finishDrag(true);
orbitState = null;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
window.addEventListener("keydown", (event) => {
if (event.key.toLowerCase() === "r") resetArrangement(true);
if (event.key.toLowerCase() === "c") resetCamera();
if (event.key.toLowerCase() === "h") {
$("hint").classList.toggle("visible");
}
});
// -------------------------------------------------------------------------
// Success effect
// -------------------------------------------------------------------------
function spawnConfetti() {
const origin = new THREE.Vector3(
targetAngle >= 0 ? 5.1 : -5.1,
0.55,
0
);
beamGroup.localToWorld(origin);
for (let i = 0; i < 34; i++) {
const mesh = new THREE.Mesh(
confettiGeometry,
confettiMaterials[i % confettiMaterials.length]
);
mesh.position.copy(origin);
mesh.position.x += (Math.random() - 0.5) * 0.5;
mesh.position.y += Math.random() * 0.4;
mesh.position.z += (Math.random() - 0.5) * 1.2;
scene.add(mesh);
confettiParticles.push({
mesh,
velocity: new THREE.Vector3(
(Math.random() - 0.5) * 3.5,
2.2 + Math.random() * 3.2,
(Math.random() - 0.5) * 3.5
),
spin: new THREE.Vector3(
Math.random() * 8,
Math.random() * 8,
Math.random() * 8
),
life: 2.3 + Math.random() * 0.8
});
}
}
function updateConfetti(dt) {
for (let i = confettiParticles.length - 1; i >= 0; i--) {
const particle = confettiParticles[i];
particle.life -= dt;
particle.velocity.y -= 4.2 * dt;
particle.mesh.position.addScaledVector(particle.velocity, dt);
particle.mesh.rotation.x += particle.spin.x * dt;
particle.mesh.rotation.y += particle.spin.y * dt;
particle.mesh.rotation.z += particle.spin.z * dt;
if (particle.life <= 0) {
scene.remove(particle.mesh);
confettiParticles.splice(i, 1);
}
}
}
// -------------------------------------------------------------------------
// Resize and animation
// -------------------------------------------------------------------------
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
updateChallengeUI();
resetArrangement(false);
currentAngle = desiredAngle;
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
updateCamera(dt);
const angleEasing = 1 - Math.exp(-8 * dt);
currentAngle += (desiredAngle - currentAngle) * angleEasing;
if (Math.abs(currentAngle - desiredAngle) < 0.001) {
currentAngle = desiredAngle;
}
// Positive challenge angle means the right side moves downward.
beamGroup.rotation.z = -THREE.MathUtils.degToRad(currentAngle);
$("needle").style.transform = `rotate(${currentAngle}deg)`;
const successful = calculateMoments().angle;
const isSuccessful = Math.abs(successful - targetAngle) < 0.02;
if (isSuccessful && !wasSuccessful) {
spawnConfetti();
showToast("Target reached!");
}
wasSuccessful = isSuccessful;
updateConfetti(dt);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```