Prompt specification
Build or customize the Three.js 3D scene "Nearest Ball Changes After Contact" 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: Nearest Ball Changes After Contact
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/nearest-ball-changes-after-contact-x3664
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts boccia balls and distance to the target jack. Create a small target-ball game where one shot can move existing balls. Recompute distances from final positions and display ties using an explicit tolerance. Low-poly.
Working Three.js Starter (nearest-ball-changes-after-contact-x3664):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Low-Poly Boccia Target Game</title>
<style>
:root {
--panel: rgba(16, 25, 31, 0.88);
--panel-border: rgba(255, 255, 255, 0.12);
--text: #f4f7f8;
--muted: #aebbc1;
--blue: #4b9cff;
--red: #ff6464;
--jack: #ffd452;
--green: #7de2a7;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #c8d4cf;
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
color: var(--text);
}
#stage {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.panel {
position: fixed;
z-index: 10;
background: var(--panel);
border: 1px solid var(--panel-border);
border-radius: 16px;
box-shadow: 0 16px 40px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
}
#controls {
top: 18px;
left: 18px;
width: 310px;
padding: 18px;
}
#scoreboard {
top: 18px;
right: 18px;
width: 330px;
padding: 16px;
max-height: calc(100vh - 36px);
overflow: auto;
}
.eyebrow {
color: #8fd7ff;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 4px 0 12px;
font-size: 25px;
line-height: 1.05;
}
h2 {
margin: 0;
font-size: 17px;
}
p {
margin: 0;
}
.phase {
display: inline-flex;
align-items: center;
gap: 7px;
margin: 0 0 12px;
padding: 6px 10px;
border-radius: 999px;
background: rgba(75, 156, 255, 0.13);
color: #a8d3ff;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.phase::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: currentColor;
content: "";
box-shadow: 0 0 12px currentColor;
}
.instructions {
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.instructions strong {
color: var(--text);
}
.power-block {
margin-top: 16px;
padding-top: 14px;
border-top: 1px solid rgba(255, 255, 255, 0.1);
}
.power-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
font-size: 13px;
font-weight: 700;
}
output {
color: #9ed0ff;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
accent-color: var(--blue);
cursor: pointer;
}
.small {
margin-top: 5px;
color: var(--muted);
font-size: 11px;
line-height: 1.4;
}
.readout {
margin-top: 11px;
padding: 9px 10px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 9px;
background: rgba(255, 255, 255, 0.04);
color: #c9d5da;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.shot-row {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 14px;
}
#shot-pips {
display: flex;
gap: 6px;
}
.pip {
width: 15px;
height: 15px;
border: 2px solid #66777f;
border-radius: 50%;
background: transparent;
}
.pip.used {
border-color: var(--blue);
background: var(--blue);
}
.pip.current {
border-color: #b9ddff;
box-shadow: 0 0 0 3px rgba(75, 156, 255, 0.16);
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 14px;
}
button {
min-height: 40px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 10px;
background: rgba(255, 255, 255, 0.07);
color: var(--text);
font: inherit;
font-size: 13px;
font-weight: 750;
cursor: pointer;
transition: transform 0.12s ease, background 0.12s ease, opacity 0.12s ease;
}
button:hover:not(:disabled) {
transform: translateY(-1px);
background: rgba(255, 255, 255, 0.12);
}
button.primary {
grid-column: 1 / -1;
background: #327fdb;
border-color: #65aaff;
}
button:disabled {
cursor: default;
opacity: 0.4;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 12px;
margin-top: 15px;
color: var(--muted);
font-size: 11px;
}
.legend span {
display: inline-flex;
align-items: center;
gap: 6px;
}
.dot {
display: inline-block;
width: 10px;
height: 10px;
border-radius: 50%;
vertical-align: -1px;
box-shadow: inset -2px -2px 3px rgba(0, 0, 0, 0.25);
}
.dot.blue { background: var(--blue); }
.dot.red { background: var(--red); }
.dot.jack { background: var(--jack); }
.score-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
}
.tolerance {
flex: 0 0 auto;
padding: 5px 7px;
border: 1px solid rgba(255, 212, 82, 0.28);
border-radius: 7px;
background: rgba(255, 212, 82, 0.09);
color: #ffe28b;
font-size: 10px;
font-weight: 800;
white-space: nowrap;
}
#leader {
margin-top: 11px;
padding: 11px 12px;
border-radius: 10px;
background: rgba(75, 156, 255, 0.1);
color: #d7eaff;
font-size: 13px;
font-weight: 700;
line-height: 1.4;
}
#official {
margin-top: 8px;
color: var(--muted);
font-size: 11px;
line-height: 1.45;
}
table {
width: 100%;
margin-top: 12px;
border-collapse: collapse;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
th {
padding: 7px 5px;
border-bottom: 1px solid rgba(255, 255, 255, 0.13);
color: var(--muted);
font-size: 10px;
letter-spacing: 0.08em;
text-align: left;
text-transform: uppercase;
}
th:nth-child(2),
td:nth-child(2) {
text-align: right;
}
td {
padding: 8px 5px;
border-bottom: 1px solid rgba(255, 255, 255, 0.06);
}
tr.closest td {
color: #fff;
background: rgba(255, 255, 255, 0.045);
}
.ball-name {
display: inline-flex;
align-items: center;
gap: 7px;
font-weight: 750;
}
.tie-badge {
display: inline-block;
min-width: 46px;
padding: 3px 5px;
border: 1px solid rgba(255, 212, 82, 0.24);
border-radius: 5px;
color: #ffe28b;
background: rgba(255, 212, 82, 0.07);
font-size: 10px;
text-align: center;
}
#toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 24px;
max-width: min(540px, calc(100vw - 30px));
padding: 11px 16px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 999px;
background: rgba(14, 22, 28, 0.92);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.3);
color: #edf5f8;
font-size: 13px;
text-align: center;
pointer-events: none;
opacity: 0;
transform: translate(-50%, 14px);
transition: opacity 0.22s ease, transform 0.22s ease;
}
#toast.show {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 760px) {
#controls {
top: 10px;
left: 10px;
width: min(285px, calc(100vw - 20px));
padding: 13px;
}
#scoreboard {
top: auto;
right: 10px;
bottom: 10px;
width: min(320px, calc(100vw - 20px));
max-height: 43vh;
padding: 12px;
}
h1 {
font-size: 21px;
}
.instructions {
font-size: 12px;
}
}
</style>
</head>
<body>
<div id="stage"></div>
<section id="controls" class="panel">
<div class="eyebrow">Low-poly target game</div>
<h1>Boccia Range</h1>
<div id="phase" class="phase">Aim B1</div>
<p class="instructions">
<strong>Left-click the court</strong> to aim and throw.
A shot can push every ball it touches, including the yellow jack.
Right-drag to orbit and scroll to zoom.
</p>
<div class="power-block">
<div class="power-row">
<label for="power">Shot power</label>
<output id="speed-out" for="power">4.7 m/s</output>
</div>
<input
id="power"
type="range"
min="3"
max="8"
step="0.1"
value="4.7"
>
<div id="power-hint" class="small"></div>
</div>
<div id="aim-readout" class="readout"></div>
<div class="shot-row">
<span class="small" style="margin: 0">Blue shots</span>
<div id="shot-pips" aria-label="Shot progress"></div>
</div>
<div class="buttons">
<button id="throw-button" class="primary">Throw shot</button>
<button id="reset-button">Reset match</button>
<button id="view-button">Reset view</button>
</div>
<div class="legend">
<span><i class="dot blue"></i>Your balls</span>
<span><i class="dot red"></i>Opponent</span>
<span><i class="dot jack"></i>Target jack</span>
</div>
</section>
<section id="scoreboard" class="panel">
<div class="score-head">
<div>
<div class="eyebrow">Final positions</div>
<h2>Distance to jack</h2>
</div>
<div class="tolerance">TIE ≤ 0.050 m</div>
</div>
<div id="leader"></div>
<div id="official"></div>
<table>
<thead>
<tr>
<th>Ball</th>
<th>Distance</th>
<th>Tie group</th>
</tr>
</thead>
<tbody id="standings-body"></tbody>
</table>
<p class="small">
Distances are recalculated after every ball settles.
Two balls are tied when their distance difference is no more than
0.050 m. Connected tie sets are grouped and labeled.
</p>
</section>
<div id="toast"></div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Configuration
// -------------------------------------------------------------------------
const TIE_TOLERANCE = 0.050;
const MAX_SHOTS = 5;
const ROLL_DECELERATION = 1.30;
const FIXED_STEP = 1 / 120;
const COURT_HALF_WIDTH = 5.5;
const COURT_HALF_LENGTH = 8.5;
const LAUNCH_POINTS = [
new THREE.Vector2(0, 6.30),
new THREE.Vector2(-2.80, 6.30),
new THREE.Vector2(2.80, 6.30),
new THREE.Vector2(0, 6.30),
new THREE.Vector2(-2.80, 6.30)
];
const TEAM_CSS = {
blue: "#4b9cff",
red: "#ff6464",
jack: "#ffd452"
};
const $ = id => document.getElementById(id);
const ui = {
phase: $("phase"),
power: $("power"),
speedOut: $("speed-out"),
powerHint: $("power-hint"),
aimReadout: $("aim-readout"),
shotPips: $("shot-pips"),
throwButton: $("throw-button"),
resetButton: $("reset-button"),
viewButton: $("view-button"),
leader: $("leader"),
official: $("official"),
standingsBody: $("standings-body"),
toast: $("toast")
};
// -------------------------------------------------------------------------
// Three.js scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xc9d6d0);
scene.fog = new THREE.Fog(0xc9d6d0, 30, 58);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
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.12;
renderer.domElement.setAttribute(
"aria-label",
"Interactive low-poly boccia court"
);
$("stage").appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
yaw: 0.32,
pitch: 0.76,
distance: 21,
target: new THREE.Vector3(0, 0, -1.2)
};
function updateCamera() {
const portraitFactor =
window.innerWidth / window.innerHeight < 0.75 ? 1.28 : 1;
const distance = cameraState.distance * portraitFactor;
const horizontalDistance =
Math.cos(cameraState.pitch) * distance;
camera.position.set(
cameraState.target.x +
Math.sin(cameraState.yaw) * horizontalDistance,
cameraState.target.y +
Math.sin(cameraState.pitch) * distance,
cameraState.target.z +
Math.cos(cameraState.yaw) * horizontalDistance
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(
0xe8f5ff,
0x66784d,
2.1
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0d4, 3.0);
sun.position.set(-8, 15, 9);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -15;
sun.shadow.camera.right = 15;
sun.shadow.camera.top = 15;
sun.shadow.camera.bottom = -15;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 45;
sun.shadow.bias = -0.0004;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xbad9ff, 0.65);
fill.position.set(10, 7, -12);
scene.add(fill);
// Low-poly court and surroundings.
const grass = new THREE.Mesh(
new THREE.BoxGeometry(50, 0.25, 50),
new THREE.MeshStandardMaterial({
color: 0x789768,
roughness: 1,
flatShading: true
})
);
grass.position.y = -0.25;
grass.receiveShadow = true;
scene.add(grass);
const court = new THREE.Mesh(
new THREE.BoxGeometry(11, 0.16, 17),
new THREE.MeshStandardMaterial({
color: 0xcba36f,
roughness: 0.94,
flatShading: true
})
);
court.position.y = -0.08;
court.receiveShadow = true;
scene.add(court);
const endZone = new THREE.Mesh(
new THREE.PlaneGeometry(10.8, 2.25),
new THREE.MeshStandardMaterial({
color: 0x6e9286,
roughness: 1
})
);
endZone.rotation.x = -Math.PI / 2;
endZone.position.set(0, 0.006, -6.75);
endZone.receiveShadow = true;
scene.add(endZone);
const lineMaterial = new THREE.MeshStandardMaterial({
color: 0xf7ead3,
roughness: 0.9
});
function addCourtLine(width, depth, x, z) {
const line = new THREE.Mesh(
new THREE.BoxGeometry(width, 0.025, depth),
lineMaterial
);
line.position.set(x, 0.012, z);
line.receiveShadow = true;
scene.add(line);
}
addCourtLine(0.07, 16.8, -5.42, 0);
addCourtLine(0.07, 16.8, 5.42, 0);
addCourtLine(10.9, 0.07, 0, -8.42);
addCourtLine(10.9, 0.07, 0, 8.42);
addCourtLine(10.8, 0.055, 0, 6.75);
const centerLine = new THREE.Mesh(
new THREE.BoxGeometry(0.035, 0.018, 16.7),
new THREE.MeshStandardMaterial({
color: 0xb4885c,
roughness: 1
})
);
centerLine.position.set(0, 0.009, 0);
scene.add(centerLine);
const launchPadMaterial = new THREE.MeshBasicMaterial({
color: 0x4b9cff,
transparent: true,
opacity: 0.23,
depthWrite: false
});
for (const point of LAUNCH_POINTS) {
const pad = new THREE.Mesh(
new THREE.RingGeometry(0.39, 0.44, 24),
launchPadMaterial
);
pad.rotation.x = -Math.PI / 2;
pad.position.set(point.x, 0.025, point.y);
scene.add(pad);
}
const launchMarker = new THREE.Mesh(
new THREE.RingGeometry(0.47, 0.54, 32),
new THREE.MeshBasicMaterial({
color: 0x8dc8ff,
transparent: true,
opacity: 0.85,
depthWrite: false
})
);
launchMarker.rotation.x = -Math.PI / 2;
scene.add(launchMarker);
const jackHalo = new THREE.Mesh(
new THREE.RingGeometry(0.45, 0.52, 32),
new THREE.MeshBasicMaterial({
color: 0xffd452,
transparent: true,
opacity: 0.72,
depthWrite: false
})
);
jackHalo.rotation.x = -Math.PI / 2;
jackHalo.position.y = 0.028;
scene.add(jackHalo);
// Aim line and endpoint.
const aimGeometry = new THREE.BufferGeometry();
aimGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(6), 3)
);
const aimLine = new THREE.Line(
aimGeometry,
new THREE.LineDashedMaterial({
color: 0xd9efff,
dashSize: 0.28,
gapSize: 0.16,
transparent: true,
opacity: 0.95
})
);
aimLine.frustumCulled = false;
scene.add(aimLine);
const aimMarker = new THREE.Mesh(
new THREE.RingGeometry(0.23, 0.31, 32),
new THREE.MeshBasicMaterial({
color: 0xe5f5ff,
transparent: true,
opacity: 0.9,
depthWrite: false
})
);
aimMarker.rotation.x = -Math.PI / 2;
scene.add(aimMarker);
// Low-poly trees around the court.
const trunkGeometry = new THREE.CylinderGeometry(
0.16, 0.23, 1.45, 5
);
const crownGeometry = new THREE.ConeGeometry(
1.12, 2.65, 7
);
const trunkMaterial = new THREE.MeshStandardMaterial({
color: 0x795438,
roughness: 1,
flatShading: true
});
const crownMaterials = [
new THREE.MeshStandardMaterial({
color: 0x3f7650,
roughness: 1,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x4d8754,
roughness: 1,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: 0x356a49,
roughness: 1,
flatShading: true
})
];
function addTree(x, z, scale, materialIndex) {
const tree = new THREE.Group();
const trunk = new THREE.Mesh(trunkGeometry, trunkMaterial);
trunk.position.y = 0.72;
trunk.castShadow = true;
tree.add(trunk);
const crown = new THREE.Mesh(
crownGeometry,
crownMaterials[materialIndex % crownMaterials.length]
);
crown.position.y = 2.05;
crown.castShadow = true;
tree.add(crown);
tree.position.set(x, 0, z);
tree.scale.setScalar(scale);
scene.add(tree);
}
addTree(-8.1, -6.8, 1.2, 0);
addTree(-9.0, 3.0, 1.0, 1);
addTree(8.4, -7.2, 1.35, 2);
addTree(8.9, 1.5, 0.95, 0);
addTree(-8.5, 8.2, 1.1, 2);
addTree(8.6, 8.1, 1.15, 1);
// -------------------------------------------------------------------------
// Ball visuals
// -------------------------------------------------------------------------
const worldGroup = new THREE.Group();
scene.add(worldGroup);
const regularBallGeometry = new THREE.IcosahedronGeometry(
0.31, 1
);
const jackGeometry = new THREE.IcosahedronGeometry(
0.23, 1
);
const seamGeometry = new THREE.TorusGeometry(
0.304, 0.009, 4, 20
);
const ballMaterials = {
blue: new THREE.MeshStandardMaterial({
color: 0x3289ef,
roughness: 0.72,
metalness: 0.02,
flatShading: true
}),
red: new THREE.MeshStandardMaterial({
color: 0xe94d4d,
roughness: 0.72,
metalness: 0.02,
flatShading: true
}),
jack: new THREE.MeshStandardMaterial({
color: 0xffcf35,
roughness: 0.68,
metalness: 0.03,
emissive: 0x5a3900,
emissiveIntensity: 0.12,
flatShading: true
})
};
const seamMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.9,
transparent: true,
opacity: 0.22,
depthWrite: false
});
function createBallMesh(team, radius, isJack) {
const group = new THREE.Group();
const ball = new THREE.Mesh(
isJack ? jackGeometry : regularBallGeometry,
ballMaterials[team]
);
ball.castShadow = true;
ball.receiveShadow = true;
group.add(ball);
if (!isJack) {
const seam = new THREE.Mesh(seamGeometry, seamMaterial);
seam.rotation.x = Math.PI / 2;
group.add(seam);
}
group.rotation.set(
Math.random() * Math.PI,
Math.random() * Math.PI,
Math.random() * Math.PI
);
return group;
}
// -------------------------------------------------------------------------
// Game and physics state
// -------------------------------------------------------------------------
let bodies = [];
let previewBody = null;
let jackBody = null;
let nextBodyId = 1;
let phase = "aim";
let shotsTaken = 0;
let lastThrownLabel = "";
let simulationElapsed = 0;
let settledElapsed = 0;
let accumulator = 0;
const aim = new THREE.Vector2(0, -2.1);
function makeBody(team, label, x, z, radius = 0.31, isJack = false) {
const body = {
id: nextBodyId++,
team,
label,
x,
z,
vx: 0,
vz: 0,
radius,
mass: 1,
isJack,
mesh: createBallMesh(team, radius, isJack)
};
body.mesh.position.set(x, radius + 0.02, z);
worldGroup.add(body.mesh);
return body;
}
function spawnPreview() {
const point = LAUNCH_POINTS[shotsTaken % LAUNCH_POINTS.length];
previewBody = makeBody(
"blue",
`B${shotsTaken + 1}`,
point.x,
point.y
);
}
function updateAimVisual() {
if (!previewBody || phase !== "aim") {
aimLine.visible = false;
aimMarker.visible = false;
launchMarker.visible = false;
return;
}
aimLine.visible = true;
aimMarker.visible = true;
launchMarker.visible = true;
const positions = aimGeometry.attributes.position.array;
positions[0] = previewBody.x;
positions[1] = 0.075;
positions[2] = previewBody.z;
positions[3] = aim.x;
positions[4] = 0.075;
positions[5] = aim.y;
aimGeometry.attributes.position.needsUpdate = true;
aimLine.computeLineDistances();
aimMarker.position.set(aim.x, 0.04, aim.y);
launchMarker.position.set(
previewBody.x,
0.04,
previewBody.z
);
const aimDistance = Math.hypot(
aim.x - previewBody.x,
aim.y - previewBody.z
);
ui.aimReadout.textContent =
`Aim line: ${aimDistance.toFixed(2)} m · ` +
`Launch speed: ${Number(ui.power.value).toFixed(1)} m/s`;
}
function updatePowerReadout() {
const speed = Number(ui.power.value);
const flatRange =
(speed * speed) / (2 * ROLL_DECELERATION);
ui.speedOut.textContent = `${speed.toFixed(1)} m/s`;
ui.powerHint.textContent =
`Approximate unobstructed roll: ${flatRange.toFixed(1)} m`;
}
function updateShotUI() {
ui.shotPips.innerHTML = "";
for (let i = 0; i < MAX_SHOTS; i++) {
const pip = document.createElement("span");
pip.className = "pip";
if (i < shotsTaken) {
pip.classList.add("used");
}
if (
phase === "aim" &&
i === shotsTaken
) {
pip.classList.add("current");
}
ui.shotPips.appendChild(pip);
}
if (phase === "moving") {
ui.phase.textContent = `${lastThrownLabel} rolling`;
} else if (phase === "done") {
ui.phase.textContent = "Match complete";
} else {
ui.phase.textContent = `Aim B${shotsTaken + 1}`;
}
ui.throwButton.disabled = phase !== "aim";
ui.power.disabled = phase !== "aim";
}
// -------------------------------------------------------------------------
// Custom 2D rigid-body physics on the court
// -------------------------------------------------------------------------
function integrateBody(body, dt) {
body.x += body.vx * dt;
body.z += body.vz * dt;
const speed = Math.hypot(body.vx, body.vz);
if (speed > 0) {
const reducedSpeed = Math.max(
0,
speed - ROLL_DECELERATION * dt
);
const factor = reducedSpeed / speed;
body.vx *= factor;
body.vz *= factor;
}
const minX = -COURT_HALF_WIDTH + body.radius;
const maxX = COURT_HALF_WIDTH - body.radius;
const minZ = -COURT_HALF_LENGTH + body.radius;
const maxZ = COURT_HALF_LENGTH - body.radius;
if (body.x < minX) {
body.x = minX;
body.vx = Math.abs(body.vx) * 0.46;
} else if (body.x > maxX) {
body.x = maxX;
body.vx = -Math.abs(body.vx) * 0.46;
}
if (body.z < minZ) {
body.z = minZ;
body.vz = Math.abs(body.vz) * 0.46;
} else if (body.z > maxZ) {
body.z = maxZ;
body.vz = -Math.abs(body.vz) * 0.46;
}
}
function resolveCollision(a, b) {
let dx = b.x - a.x;
let dz = b.z - a.z;
const minimumDistance = a.radius + b.radius;
const distanceSquared = dx * dx + dz * dz;
if (distanceSquared >= minimumDistance * minimumDistance) {
return;
}
let distance = Math.sqrt(distanceSquared);
let nx;
let nz;
if (distance > 0.000001) {
nx = dx / distance;
nz = dz / distance;
} else {
nx = a.id < b.id ? 1 : -1;
nz = 0;
distance = 0;
}
const inverseA = 1 / a.mass;
const inverseB = 1 / b.mass;
const inverseTotal = inverseA + inverseB;
// Positional correction prevents overlapping balls.
const penetration = minimumDistance - distance;
const correction = (penetration * 0.86) / inverseTotal;
a.x -= nx * correction * inverseA;
a.z -= nz * correction * inverseA;
b.x += nx * correction * inverseB;
b.z += nz * correction * inverseB;
const relativeVelocityX = b.vx - a.vx;
const relativeVelocityZ = b.vz - a.vz;
const velocityAlongNormal =
relativeVelocityX * nx + relativeVelocityZ * nz;
if (velocityAlongNormal < 0) {
// The jack collision is nearly inelastic, so a direct shot can
// move the jack while the shooting ball remains close to it.
const restitution =
a.isJack || b.isJack ? 0.02 : 0.48;
const impulseMagnitude =
-(1 + restitution) *
velocityAlongNormal /
inverseTotal;
a.vx -= impulseMagnitude * inverseA * nx;
a.vz -= impulseMagnitude * inverseA * nz;
b.vx += impulseMagnitude * inverseB * nx;
b.vz += impulseMagnitude * inverseB * nz;
}
}
function stepPhysics(dt) {
for (const body of bodies) {
integrateBody(body, dt);
}
for (let i = 0; i < bodies.length; i++) {
for (let j = i + 1; j < bodies.length; j++) {
resolveCollision(bodies[i], bodies[j]);
}
}
for (const body of bodies) {
body.mesh.position.set(
body.x,
body.radius + 0.02,
body.z
);
body.mesh.rotation.z -= (body.vx * dt) / body.radius;
body.mesh.rotation.x += (body.vz * dt) / body.radius;
}
simulationElapsed += dt;
const allSlow = bodies.every(body => {
return Math.hypot(body.vx, body.vz) < 0.025;
});
settledElapsed = allSlow ? settledElapsed + dt : 0;
if (
settledElapsed > 0.48 ||
simulationElapsed > 14
) {
finalizeShot();
}
}
function throwShot() {
if (phase !== "aim" || !previewBody) {
return;
}
const directionX = aim.x - previewBody.x;
const directionZ = aim.y - previewBody.z;
const directionLength = Math.hypot(directionX, directionZ);
let unitX = 0;
let unitZ = -1;
if (directionLength > 0.0001) {
unitX = directionX / directionLength;
unitZ = directionZ / directionLength;
}
const speed = Number(ui.power.value);
previewBody.vx = unitX * speed;
previewBody.vz = unitZ * speed;
lastThrownLabel = previewBody.label;
bodies.push(previewBody);
previewBody = null;
shotsTaken++;
phase = "moving";
simulationElapsed = 0;
settledElapsed = 0;
updateShotUI();
updateAimVisual();
showToast(
`${lastThrownLabel} thrown at ${speed.toFixed(1)} m/s`
);
}
function finalizeShot() {
for (const body of bodies) {
body.vx = 0;
body.vz = 0;
body.mesh.position.set(
body.x,
body.radius + 0.02,
body.z
);
}
phase = shotsTaken < MAX_SHOTS ? "aim" : "done";
if (phase === "aim") {
spawnPreview();
}
updateShotUI();
updateAimVisual();
const analysis = updateStandings();
const thrownBody = bodies.find(
body => body.label === lastThrownLabel
);
const thrownDistance =
thrownBody && jackBody
? Math.hypot(
thrownBody.x - jackBody.x,
thrownBody.z - jackBody.z
)
: 0;
if (phase === "done") {
showToast(
`Match complete. ${analysis.officialText}`,
"success"
);
} else {
showToast(
`${lastThrownLabel} settled at ` +
`${thrownDistance.toFixed(3)} m. ` +
analysis.leaderText,
"success"
);
}
}
// -------------------------------------------------------------------------
// Distance, tie, and score calculations
// -------------------------------------------------------------------------
function analyzeStandings() {
const items = bodies
.filter(body => !body.isJack)
.map(body => ({
...body,
distance: jackBody
? Math.hypot(
body.x - jackBody.x,
body.z - jackBody.z
)
: Infinity
}))
.sort((a, b) => a.distance - b.distance);
// Union-find groups pairwise ties whose gap is within the
// explicit tolerance. Connected components form tie groups.
const parent = items.map((_, index) => index);
function find(index) {
while (parent[index] !== index) {
parent[index] = parent[parent[index]];
index = parent[index];
}
return index;
}
function union(a, b) {
const rootA = find(a);
const rootB = find(b);
if (rootA !== rootB) {
parent[rootB] = rootA;
}
}
for (let i = 0; i < items.length; i++) {
for (let j = i + 1; j < items.length; j++) {
if (
Math.abs(items[i].distance - items[j].distance)
<= TIE_TOLERANCE
) {
union(i, j);
}
}
}
const components = new Map();
items.forEach((item, index) => {
const root = find(index);
if (!components.has(root)) {
components.set(root, []);
}
components.get(root).push(item);
});
const tieInfo = new Map();
const groups = [...components.values()]
.filter(group => group.length > 1)
.sort(
(a, b) =>
items.indexOf(a[0]) - items.indexOf(b[0])
);
groups.forEach((group, index) => {
const letter = String.fromCharCode(65 + index);
for (const member of group) {
tieInfo.set(member.id, {
letter,
members: group
});
}
});
const minimumDistance = items.length
? items[0].distance
: Infinity;
const closestContenders = items.filter(
item =>
Math.abs(item.distance - minimumDistance)
<= TIE_TOLERANCE
);
let leaderText = "No balls on the court yet.";
if (items.length > 0) {
if (closestContenders.length > 1) {
const names = closestContenders
.map(item => item.label)
.join(" + ");
const teams = new Set(
closestContenders.map(item => item.team)
);
if (teams.has("blue") && teams.has("red")) {
leaderText = `Shared tie: ${names}`;
} else {
const team =
closestContenders[0].team === "blue"
? "Blue"
: "Red";
leaderText = `${team} tie: ${names}`;
}
} else {
const leader = closestContenders[0];
const team =
leader.team === "blue" ? "Blue" : "Red";
leaderText =
`${team} ${leader.label} leads at ` +
`${leader.distance.toFixed(3)} m`;
}
}
let officialText =
"Official score is calculated after all five blue shots.";
if (phase === "done") {
const blue = items
.filter(item => item.team === "blue")
.sort((a, b) => a.distance - b.distance);
const red = items
.filter(item => item.team === "red")
.sort((a, b) => a.distance - b.distance);
if (blue.length && red.length) {
const closestDifference = Math.abs(
blue[0].distance - red[0].distance
);
if (closestDifference <= TIE_TOLERANCE) {
officialText =
"Final score — shared tie, 0–0.";
} else {
const blueWins =
blue[0].distance < red[0].distance;
const winner = blueWins ? blue : red;
const loser = blueWins ? red : blue;
const winnerPoints =
winner.length >= 2 &&
winner[1].distance + TIE_TOLERANCE <
loser[0].distance
? 2
: 1;
officialText = blueWins
? `Final score — Blue ${winnerPoints} : 0 Red`
: `Final score — Blue 0 : ${winnerPoints} Red`;
}
}
}
return {
items,
tieInfo,
closestContenders,
leaderText,
officialText
};
}
function updateStandings() {
const analysis = analyzeStandings();
ui.standingsBody.innerHTML = "";
analysis.items.forEach((item, index) => {
const row = document.createElement("tr");
if (index === 0) {
row.className = "closest";
}
const nameCell = document.createElement("td");
nameCell.innerHTML =
`<span class="ball-name">` +
`<i class="dot ${item.team}"></i>` +
`${item.label}</span>`;
const distanceCell = document.createElement("td");
distanceCell.textContent = `${item.distance.toFixed(3)} m`;
const tieCell = document.createElement("td");
const group = analysis.tieInfo.get(item.id);
if (group) {
tieCell.innerHTML =
`<span class="tie-badge">` +
`${group.letter} · ${group.members.length}</span>`;
tieCell.title = group.members
.map(member => member.label)
.join(", ");
} else {
tieCell.textContent = "—";
}
row.append(nameCell, distanceCell, tieCell);
ui.standingsBody.appendChild(row);
});
ui.leader.textContent = analysis.leaderText;
ui.official.textContent = analysis.officialText;
return analysis;
}
// -------------------------------------------------------------------------
// Pointer aiming and custom camera controls
// -------------------------------------------------------------------------
const pointer = new THREE.Vector2();
const raycaster = new THREE.Raycaster();
const aimPlane = new THREE.Plane(
new THREE.Vector3(0, 1, 0),
0
);
const aimHit = new THREE.Vector3();
let orbiting = false;
let orbitPointerId = null;
let previousPointerX = 0;
let previousPointerY = 0;
function updateAimFromPointer(event) {
if (!previewBody || phase !== "aim") {
return;
}
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);
if (raycaster.ray.intersectPlane(aimPlane, aimHit)) {
aim.x = THREE.MathUtils.clamp(
aimHit.x,
-COURT_HALF_WIDTH + 0.1,
COURT_HALF_WIDTH - 0.1
);
aim.y = THREE.MathUtils.clamp(
aimHit.z,
-COURT_HALF_LENGTH + 0.1,
COURT_HALF_LENGTH - 0.1
);
updateAimVisual();
}
}
renderer.domElement.addEventListener("pointermove", event => {
if (orbiting && event.pointerId === orbitPointerId) {
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
cameraState.yaw -= deltaX * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + deltaY * 0.005,
0.38,
1.22
);
previousPointerX = event.clientX;
previousPointerY = event.clientY;
updateCamera();
return;
}
updateAimFromPointer(event);
});
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button === 2) {
orbiting = true;
orbitPointerId = event.pointerId;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
return;
}
if (event.button === 0) {
updateAimFromPointer(event);
throwShot();
}
});
function stopOrbit(event) {
if (
orbiting &&
event.pointerId === orbitPointerId
) {
orbiting = false;
orbitPointerId = null;
if (
renderer.domElement.hasPointerCapture(
event.pointerId
)
) {
renderer.domElement.releasePointerCapture(
event.pointerId
);
}
}
}
renderer.domElement.addEventListener(
"pointerup",
stopOrbit
);
renderer.domElement.addEventListener(
"pointercancel",
stopOrbit
);
renderer.domElement.addEventListener(
"contextmenu",
event => event.preventDefault()
);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.012,
13,
29
);
updateCamera();
}, { passive: false });
// -------------------------------------------------------------------------
// Reset and UI events
// -------------------------------------------------------------------------
let toastTimer = null;
function showToast(message, tone = "") {
clearTimeout(toastTimer);
ui.toast.textContent = message;
ui.toast.classList.toggle("success", tone === "success");
ui.toast.classList.add("show");
toastTimer = setTimeout(() => {
ui.toast.classList.remove("show");
}, 3200);
}
function resetMatch() {
while (worldGroup.children.length > 0) {
worldGroup.remove(worldGroup.children[0]);
}
bodies = [];
previewBody = null;
nextBodyId = 1;
shotsTaken = 0;
lastThrownLabel = "";
phase = "aim";
simulationElapsed = 0;
settledElapsed = 0;
accumulator = 0;
jackBody = makeBody(
"jack",
"Jack",
0,
-2.10,
0.23,
true
);
// Register the existing jack and red balls in physics and standings.
bodies.push(
jackBody,
makeBody("red", "R1", -0.636396, -2.10),
makeBody("red", "R2", 0.636396, -2.10),
makeBody("red", "R3", -1.25, -3.15)
);
aim.set(jackBody.x, jackBody.z);
spawnPreview();
updatePowerReadout();
updateShotUI();
updateAimVisual();
updateStandings();
showToast(
"New match. Five blue shots; the yellow jack is the target."
);
}
ui.throwButton.addEventListener("click", throwShot);
ui.resetButton.addEventListener("click", resetMatch);
ui.power.addEventListener("input", () => {
updatePowerReadout();
updateAimVisual();
});
ui.viewButton.addEventListener("click", () => {
cameraState.yaw = 0.32;
cameraState.pitch = 0.76;
cameraState.distance = 21;
updateCamera();
});
document.addEventListener("keydown", event => {
const tag = event.target.tagName;
if (
tag === "INPUT" ||
tag === "TEXTAREA" ||
tag === "SELECT"
) {
return;
}
if (event.code === "Space") {
event.preventDefault();
throwShot();
}
if (event.key.toLowerCase() === "r") {
resetMatch();
}
});
window.addEventListener("resize", () => {
camera.aspect =
window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(
window.innerWidth,
window.innerHeight
);
renderer.setPixelRatio(
Math.min(window.devicePixelRatio, 2)
);
updateCamera();
});
// -------------------------------------------------------------------------
// Render loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const frameDelta = Math.min(clock.getDelta(), 0.05);
if (phase === "moving") {
accumulator += frameDelta;
while (
accumulator >= FIXED_STEP &&
phase === "moving"
) {
stepPhysics(FIXED_STEP);
accumulator -= FIXED_STEP;
}
} else {
accumulator = 0;
}
if (jackBody) {
jackHalo.position.set(
jackBody.x,
0.028,
jackBody.z
);
}
renderer.render(scene, camera);
}
resetMatch();
animate();
</script>
</body>
</html>
```