Prompt specification
Build or customize the Three.js 3D scene "Projectile trajectory and coordinate frame" 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: Projectile trajectory and coordinate frame
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/projectile-trajectory-and-coordinate-frame-x1417
Scene Description Prompt:
Projectile trajectory and coordinate frame. Place a launch point, ground plane, and axis arrows beside an analytically sampled parabolic path; state uniform gravity and neglected air resistance explicitly. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (projectile-trajectory-and-coordinate-frame-x1417):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Projectile Trajectory — Coordinate Frame</title>
<style>
:root {
color-scheme: dark;
--bg: #07111b;
--panel: rgba(9, 20, 32, 0.88);
--border: rgba(157, 196, 226, 0.18);
--text: #e9f4ff;
--muted: #91a8bc;
--accent: #ffb24a;
--cyan: #62d9ff;
--green: #70e6b4;
--red: #ff746c;
--blue: #69aaff;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
outline: none;
}
#loading {
position: fixed;
inset: 0;
z-index: 100;
display: grid;
place-items: center;
background: #07111b;
color: var(--muted);
letter-spacing: 0.08em;
transition: opacity 250ms ease;
}
.panel {
position: fixed;
z-index: 10;
top: 18px;
left: 18px;
width: 350px;
max-height: calc(100vh - 36px);
overflow-y: auto;
padding: 18px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 18px 55px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(16px);
scrollbar-width: thin;
scrollbar-color: #385166 transparent;
}
.eyebrow {
margin-bottom: 5px;
color: var(--accent);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 23px;
line-height: 1.15;
letter-spacing: -0.025em;
}
.subtitle {
margin: 8px 0 16px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.section-label {
margin: 17px 0 9px;
color: #a9c0d4;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.control {
margin: 11px 0;
}
.control-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 6px;
font-size: 12px;
}
.control-row output {
color: var(--cyan);
font-variant-numeric: tabular-nums;
font-weight: 700;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 4px 0;
accent-color: var(--accent);
cursor: pointer;
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 10px;
}
button {
min-height: 38px;
padding: 8px 11px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
cursor: pointer;
font-size: 12px;
font-weight: 700;
transition:
background 150ms ease,
border-color 150ms ease,
transform 100ms ease;
}
button:hover {
background: rgba(255, 255, 255, 0.1);
border-color: rgba(157, 196, 226, 0.34);
}
button:active {
transform: translateY(1px);
}
button.primary {
border-color: rgba(255, 178, 74, 0.45);
background: rgba(255, 178, 74, 0.14);
color: #ffd194;
}
button.active {
border-color: var(--cyan);
background: rgba(98, 217, 255, 0.16);
color: #c9f3ff;
}
.wide {
width: 100%;
margin-top: 8px;
}
.stats {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.stat {
min-width: 0;
padding: 9px 8px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.035);
}
.stat-label {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat-value {
display: block;
overflow: hidden;
color: var(--text);
font-size: 15px;
font-weight: 750;
font-variant-numeric: tabular-nums;
text-overflow: ellipsis;
white-space: nowrap;
}
.coordinate-readout {
margin-top: 7px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
}
.formula {
padding: 11px 12px;
border: 1px solid rgba(98, 217, 255, 0.18);
border-radius: 11px;
background: rgba(98, 217, 255, 0.055);
color: #ccefff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
line-height: 1.6;
}
.assumptions {
margin-top: 9px;
color: var(--muted);
font-size: 11px;
line-height: 1.55;
}
.assumptions strong {
color: var(--green);
}
.legend {
position: fixed;
z-index: 8;
top: 18px;
right: 18px;
padding: 12px 14px;
border: 1px solid var(--border);
border-radius: 14px;
background: rgba(9, 20, 32, 0.76);
backdrop-filter: blur(12px);
color: var(--muted);
font-size: 11px;
line-height: 1.9;
}
.legend-row {
display: flex;
align-items: center;
gap: 8px;
}
.swatch {
width: 18px;
height: 3px;
border-radius: 3px;
}
.help {
position: fixed;
z-index: 8;
right: 18px;
bottom: 16px;
padding: 9px 12px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(9, 20, 32, 0.72);
color: var(--muted);
font-size: 11px;
backdrop-filter: blur(10px);
}
#toast {
position: fixed;
z-index: 30;
left: 50%;
bottom: 22px;
transform: translate(-50%, 12px);
padding: 10px 14px;
border: 1px solid rgba(98, 217, 255, 0.3);
border-radius: 10px;
background: rgba(9, 20, 32, 0.93);
color: #d9f5ff;
font-size: 12px;
opacity: 0;
pointer-events: none;
transition:
opacity 180ms ease,
transform 180ms ease;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 760px) {
.panel {
top: 12px;
left: 12px;
width: min(350px, calc(100vw - 24px));
max-height: calc(100vh - 24px);
padding: 14px;
}
.legend,
.help {
display: none;
}
}
</style>
</head>
<body>
<div id="viewport"></div>
<div id="loading">LOADING THREE.JS…</div>
<aside class="panel">
<div class="eyebrow">Trajectory Lab</div>
<h1>Analytic Projectile</h1>
<p class="subtitle">
A low-poly, coordinate-based view of a parabolic flight path.
Move the launch point or change the initial velocity.
</p>
<div class="section-label">Launch conditions</div>
<div class="control">
<div class="control-row">
<label for="speed">Initial speed</label>
<output id="speedOut">20 m/s</output>
</div>
<input id="speed" type="range" min="8" max="30" step="0.5" value="20">
</div>
<div class="control">
<div class="control-row">
<label for="elevation">Elevation angle</label>
<output id="elevationOut">42°</output>
</div>
<input id="elevation" type="range" min="8" max="78" step="1" value="42">
</div>
<div class="control">
<div class="control-row">
<label for="azimuth">Azimuth from +X</label>
<output id="azimuthOut">0°</output>
</div>
<input id="azimuth" type="range" min="-180" max="180" step="1" value="0">
</div>
<div class="control">
<div class="control-row">
<label for="height">Launch height</label>
<output id="heightOut">0.8 m</output>
</div>
<input id="height" type="range" min="0" max="6" step="0.1" value="0.8">
</div>
<div class="button-row">
<button id="playBtn" class="primary" type="button">▶ Play motion</button>
<button id="placeBtn" type="button">⌖ Place launch</button>
</div>
<button id="resetBtn" class="wide" type="button">Reset launch point</button>
<div class="section-label">Flight timeline</div>
<input id="timeScrub" type="range" min="0" max="1000" step="1" value="0"
aria-label="Projectile time">
<div class="section-label">Measured results</div>
<div class="stats">
<div class="stat">
<span class="stat-label">Flight time</span>
<span id="flightTime" class="stat-value">—</span>
</div>
<div class="stat">
<span class="stat-label">Range</span>
<span id="rangeValue" class="stat-value">—</span>
</div>
<div class="stat">
<span class="stat-label">Max height</span>
<span id="apexValue" class="stat-value">—</span>
</div>
</div>
<div id="coordinates" class="coordinate-readout">r₀ = (—)</div>
<div class="section-label">Analytic model</div>
<div class="formula">
r(t) = r₀ + v₀t + ½gt²<br>
g = (0, −9.81, 0) m/s²<br>
r(t) sampled directly from the equation.
</div>
<div class="assumptions">
<strong>Uniform gravity:</strong> g = 9.81 m/s² downward in −Y.<br>
<strong>Air resistance neglected:</strong> no drag, wind, or lift.
</div>
</aside>
<div class="legend">
<div class="legend-row">
<span class="swatch" style="background:#ff746c"></span>
+X axis
</div>
<div class="legend-row">
<span class="swatch" style="background:#70e6b4"></span>
+Y axis / up
</div>
<div class="legend-row">
<span class="swatch" style="background:#69aaff"></span>
+Z axis
</div>
<div class="legend-row">
<span class="swatch" style="background:#ffb24a"></span>
Analytic trajectory
</div>
</div>
<div class="help">
Drag: orbit · Wheel: zoom · Right-drag or Shift-drag: pan · Space: play/pause
</div>
<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";
// ---------------------------------------------------------------------
// Constants and application state
// ---------------------------------------------------------------------
const GRAVITY = 9.81;
const PATH_SAMPLES = 72;
const INITIAL_LAUNCH = { x: -18, z: 10 };
const params = {
speed: 20,
elevation: 42,
azimuth: 0,
height: 0.8,
launchX: INITIAL_LAUNCH.x,
launchZ: INITIAL_LAUNCH.z
};
const viewport = document.querySelector("#viewport");
const loading = document.querySelector("#loading");
const toast = document.querySelector("#toast");
const ui = {
speed: document.querySelector("#speed"),
elevation: document.querySelector("#elevation"),
azimuth: document.querySelector("#azimuth"),
height: document.querySelector("#height"),
speedOut: document.querySelector("#speedOut"),
elevationOut: document.querySelector("#elevationOut"),
azimuthOut: document.querySelector("#azimuthOut"),
heightOut: document.querySelector("#heightOut"),
playBtn: document.querySelector("#playBtn"),
placeBtn: document.querySelector("#placeBtn"),
resetBtn: document.querySelector("#resetBtn"),
timeScrub: document.querySelector("#timeScrub"),
flightTime: document.querySelector("#flightTime"),
rangeValue: document.querySelector("#rangeValue"),
apexValue: document.querySelector("#apexValue"),
coordinates: document.querySelector("#coordinates")
};
let placementMode = false;
let playing = false;
let simTime = 0;
let impactHold = 0;
let flightData = null;
// ---------------------------------------------------------------------
// Renderer, scene, and camera
// ---------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setClearColor(0x07111b, 1);
viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111b);
scene.fog = new THREE.Fog(0x07111b, 82, 170);
const camera = new THREE.PerspectiveCamera(
46,
window.innerWidth / window.innerHeight,
0.1,
300
);
const cameraTarget = new THREE.Vector3(1, 4, 6);
let cameraRadius = 61;
let cameraTheta = -0.72;
let cameraPhi = 1.02;
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);
camera.updateMatrixWorld();
}
updateCamera();
// ---------------------------------------------------------------------
// Lighting
// ---------------------------------------------------------------------
const hemisphere = new THREE.HemisphereLight(
0xb9ddff,
0x16202a,
1.65
);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffe6c4, 2.7);
sun.position.set(-24, 42, 28);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -50;
sun.shadow.camera.right = 50;
sun.shadow.camera.top = 50;
sun.shadow.camera.bottom = -50;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 130;
sun.shadow.bias = -0.0004;
scene.add(sun);
const rimLight = new THREE.DirectionalLight(0x4b9dff, 1.1);
rimLight.position.set(30, 18, -35);
scene.add(rimLight);
// ---------------------------------------------------------------------
// Ground plane and coordinate grid
// ---------------------------------------------------------------------
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x111f2a,
roughness: 0.93,
metalness: 0.02,
flatShading: true
});
const groundMesh = new THREE.Mesh(
new THREE.BoxGeometry(90, 0.4, 90),
groundMaterial
);
groundMesh.position.y = -0.2;
groundMesh.receiveShadow = true;
scene.add(groundMesh);
const groundEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(groundMesh.geometry),
new THREE.LineBasicMaterial({
color: 0x29475d,
transparent: true,
opacity: 0.55
})
);
groundEdges.position.copy(groundMesh.position);
scene.add(groundEdges);
const grid = new THREE.GridHelper(90, 45, 0x3d6d86, 0x20384a);
grid.position.y = 0.012;
const gridMaterials = Array.isArray(grid.material)
? grid.material
: [grid.material];
gridMaterials.forEach((material) => {
material.transparent = true;
material.opacity = 0.36;
});
scene.add(grid);
// ---------------------------------------------------------------------
// Small helpers for low-poly arrows, labels, and dashed lines
// ---------------------------------------------------------------------
function makeLabel(text, color = 0xffffff, scale = 0.7) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 160;
const context = canvas.getContext("2d");
const cssColor = new THREE.Color(color).getStyle();
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(5, 12, 20, 0.82)";
context.fillRect(8, 8, 496, 144);
context.strokeStyle = cssColor;
context.lineWidth = 4;
context.strokeRect(8, 8, 496, 144);
context.fillStyle = cssColor;
context.font = "700 62px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 82);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(scale * 2.25, scale * 0.70, 1);
sprite.renderOrder = 20;
return sprite;
}
function makeArrow(
origin,
direction,
length,
color,
text = null,
radius = 0.065,
labelScale = 0.62
) {
const group = new THREE.Group();
const directionNormalized = direction.clone().normalize();
const headLength = Math.min(length * 0.19, 0.72);
const bodyLength = Math.max(length - headLength, 0.01);
const headRadius = radius * 3.4;
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.2,
roughness: 0.48,
metalness: 0.12,
flatShading: true
});
const body = new THREE.Mesh(
new THREE.CylinderGeometry(
radius,
radius,
bodyLength,
6,
1,
false
),
material
);
const head = new THREE.Mesh(
new THREE.CylinderGeometry(
0,
headRadius,
headLength,
4,
1,
false
),
material
);
const quaternion = new THREE.Quaternion().setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
directionNormalized
);
body.quaternion.copy(quaternion);
head.quaternion.copy(quaternion);
body.position.copy(directionNormalized)
.multiplyScalar(bodyLength / 2)
.add(origin);
head.position.copy(directionNormalized)
.multiplyScalar(bodyLength + headLength / 2)
.add(origin);
body.castShadow = true;
head.castShadow = true;
group.add(body, head);
if (text) {
const label = makeLabel(text, color, labelScale);
label.position.copy(directionNormalized)
.multiplyScalar(length + 0.55)
.add(origin);
group.add(label);
}
return group;
}
function makeDashedLine(start, end, color, opacity = 0.65) {
const geometry = new THREE.BufferGeometry().setFromPoints([
start,
end
]);
const material = new THREE.LineDashedMaterial({
color,
dashSize: 0.36,
gapSize: 0.24,
transparent: true,
opacity
});
const line = new THREE.Line(geometry, material);
line.computeLineDistances();
return line;
}
function updateLineGeometry(line, points) {
line.geometry.dispose();
line.geometry = new THREE.BufferGeometry().setFromPoints(points);
if (line.material.isLineDashedMaterial) {
line.computeLineDistances();
}
}
function disposeObject(object) {
object.traverse((child) => {
if (child.geometry) {
child.geometry.dispose();
}
if (child.material) {
const materials = Array.isArray(child.material)
? child.material
: [child.material];
materials.forEach((material) => {
if (material.map) {
material.map.dispose();
}
material.dispose();
});
}
});
}
function clearGroup(group) {
while (group.children.length) {
const child = group.children.pop();
disposeObject(child);
}
}
// ---------------------------------------------------------------------
// World coordinate frame: X right, Y up, Z lateral
// ---------------------------------------------------------------------
const axes = new THREE.Group();
axes.position.set(0, 0.03, 0);
scene.add(axes);
axes.add(
makeArrow(
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(1, 0, 0),
9,
0xff746c,
"X"
)
);
axes.add(
makeArrow(
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(0, 1, 0),
6,
0x70e6b4,
"Y"
)
);
axes.add(
makeArrow(
new THREE.Vector3(0, 0, 0),
new THREE.Vector3(0, 0, 1),
9,
0x69aaff,
"Z"
)
);
const origin = new THREE.Mesh(
new THREE.OctahedronGeometry(0.24, 0),
new THREE.MeshStandardMaterial({
color: 0xe9f4ff,
emissive: 0x446070,
emissiveIntensity: 0.5,
flatShading: true
})
);
origin.position.y = 0.25;
origin.castShadow = true;
axes.add(origin);
const originLabel = makeLabel("O", 0xe9f4ff, 0.45);
originLabel.position.set(0, 0.85, 0);
axes.add(originLabel);
// ---------------------------------------------------------------------
// Launch-point marker
// ---------------------------------------------------------------------
const launchMarker = new THREE.Group();
scene.add(launchMarker);
const launchBase = new THREE.Mesh(
new THREE.CylinderGeometry(0.62, 0.76, 0.2, 8),
new THREE.MeshStandardMaterial({
color: 0x536a7b,
roughness: 0.74,
flatShading: true
})
);
launchBase.position.y = 0.1;
launchBase.castShadow = true;
launchBase.receiveShadow = true;
launchMarker.add(launchBase);
const launchBaseRing = new THREE.Mesh(
new THREE.TorusGeometry(0.58, 0.065, 6, 16),
new THREE.MeshStandardMaterial({
color: 0x70e6b4,
emissive: 0x70e6b4,
emissiveIntensity: 0.35,
flatShading: true
})
);
launchBaseRing.rotation.x = Math.PI / 2;
launchBaseRing.position.y = 0.22;
launchMarker.add(launchBaseRing);
const launchPole = new THREE.Mesh(
new THREE.CylinderGeometry(0.045, 0.045, 1, 6),
new THREE.MeshStandardMaterial({
color: 0x83a0b5,
roughness: 0.5,
flatShading: true
})
);
launchPole.castShadow = true;
launchMarker.add(launchPole);
const launchBeacon = new THREE.Mesh(
new THREE.OctahedronGeometry(0.28, 0),
new THREE.MeshStandardMaterial({
color: 0xffe29a,
emissive: 0xffb24a,
emissiveIntensity: 0.8,
roughness: 0.32,
flatShading: true
})
);
launchBeacon.castShadow = true;
launchMarker.add(launchBeacon);
const launchHalo = new THREE.Mesh(
new THREE.TorusGeometry(0.48, 0.035, 4, 16),
new THREE.MeshBasicMaterial({
color: 0xffd27b,
transparent: true,
opacity: 0.9
})
);
launchHalo.rotation.x = Math.PI / 2;
launchMarker.add(launchHalo);
const launchLabel = makeLabel("LAUNCH", 0xffd27b, 0.5);
launchMarker.add(launchLabel);
const launchGuide = makeDashedLine(
new THREE.Vector3(),
new THREE.Vector3(),
0x70e6b4,
0.7
);
scene.add(launchGuide);
function updateLaunchMarker() {
launchMarker.position.set(params.launchX, 0, params.launchZ);
launchPole.scale.y = Math.max(params.height, 0.001);
launchPole.position.y = params.height / 2;
launchBeacon.position.y = params.height;
launchHalo.position.y = params.height;
launchLabel.position.set(0, params.height + 0.95, 0);
updateLineGeometry(launchGuide, [
new THREE.Vector3(params.launchX, 0.03, params.launchZ),
new THREE.Vector3(
params.launchX,
Math.max(params.height, 0.03),
params.launchZ
)
]);
}
// ---------------------------------------------------------------------
// Moving projectile
// ---------------------------------------------------------------------
const projectile = new THREE.Group();
scene.add(projectile);
const projectileBody = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.24, 0),
new THREE.MeshStandardMaterial({
color: 0xfff3d5,
emissive: 0xff9d38,
emissiveIntensity: 0.75,
roughness: 0.34,
metalness: 0.05,
flatShading: true
})
);
projectileBody.castShadow = true;
projectile.add(projectileBody);
const projectileLight = new THREE.PointLight(0xffa64d, 1.3, 4);
projectile.add(projectileLight);
// ---------------------------------------------------------------------
// Dynamic trajectory objects
// ---------------------------------------------------------------------
const dynamicGroup = new THREE.Group();
scene.add(dynamicGroup);
// ---------------------------------------------------------------------
// Analytic projectile calculation
// ---------------------------------------------------------------------
function calculateFlight() {
const elevation = THREE.MathUtils.degToRad(params.elevation);
const azimuth = THREE.MathUtils.degToRad(params.azimuth);
const horizontalSpeed = params.speed * Math.cos(elevation);
const vx = horizontalSpeed * Math.cos(azimuth);
const vy = params.speed * Math.sin(elevation);
const vz = horizontalSpeed * Math.sin(azimuth);
// Positive root of:
// launchY + vy*t - 0.5*g*t^2 = 0
const discriminant = vy * vy + 2 * GRAVITY * params.height;
const impactTime = (vy + Math.sqrt(discriminant)) / GRAVITY;
const apexTime = Math.max(vy, 0) / GRAVITY;
const apexY = params.height + Math.max(vy, 0) ** 2 / (2 * GRAVITY);
const horizontalRange = Math.hypot(vx, vz) * impactTime;
return {
vx,
vy,
vz,
impactTime,
apexTime,
apexY,
horizontalRange,
azimuth
};
}
function pointAtTime(data, time, target = new THREE.Vector3()) {
return target.set(
params.launchX + data.vx * time,
params.height + data.vy * time - 0.5 * GRAVITY * time * time,
params.launchZ + data.vz * time
);
}
// ---------------------------------------------------------------------
// Low-poly square-section tube around the analytically sampled path
// ---------------------------------------------------------------------
function buildTrajectoryMesh(points, azimuth) {
const radius = 0.12;
const positions = [];
const indices = [];
// Constant vector perpendicular to the vertical trajectory plane.
const lateral = new THREE.Vector3(
-Math.sin(azimuth),
0,
Math.cos(azimuth)
).normalize();
const tangent = new THREE.Vector3();
const binormal = new THREE.Vector3();
const corner = new THREE.Vector3();
for (let i = 0; i < points.length; i++) {
if (i === 0) {
tangent.subVectors(points[1], points[0]);
} else if (i === points.length - 1) {
tangent.subVectors(points[i], points[i - 1]);
} else {
tangent.subVectors(points[i + 1], points[i - 1]);
}
tangent.normalize();
binormal.crossVectors(tangent, lateral).normalize();
for (let side = 0; side < 4; side++) {
const angle = side * Math.PI / 2;
corner.copy(points[i])
.addScaledVector(lateral, Math.cos(angle) * radius)
.addScaledVector(binormal, Math.sin(angle) * radius);
positions.push(corner.x, corner.y, corner.z);
}
}
for (let i = 0; i < points.length - 1; i++) {
for (let side = 0; side < 4; side++) {
const nextSide = (side + 1) % 4;
const a = i * 4 + side;
const b = i * 4 + nextSide;
const c = (i + 1) * 4 + side;
const d = (i + 1) * 4 + nextSide;
indices.push(a, b, d, a, d, c);
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
geometry.computeVertexNormals();
const material = new THREE.MeshStandardMaterial({
color: 0xffad42,
emissive: 0xd96913,
emissiveIntensity: 0.42,
roughness: 0.4,
metalness: 0.05,
flatShading: true
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function buildImpactMarker(position) {
const group = new THREE.Group();
group.position.set(position.x, 0.03, position.z);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(0.58, 0.72, 0.16, 8),
new THREE.MeshStandardMaterial({
color: 0x3a6475,
emissive: 0x173c49,
emissiveIntensity: 0.4,
roughness: 0.72,
flatShading: true
})
);
base.position.y = 0.08;
base.castShadow = true;
base.receiveShadow = true;
group.add(base);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.54, 0.065, 6, 16),
new THREE.MeshStandardMaterial({
color: 0x62d9ff,
emissive: 0x297f9e,
emissiveIntensity: 0.55,
flatShading: true
})
);
ring.rotation.x = Math.PI / 2;
ring.position.y = 0.2;
group.add(ring);
const label = makeLabel("IMPACT", 0x62d9ff, 0.48);
label.position.set(0, 1.05, 0);
group.add(label);
return group;
}
function buildApexMarker(position) {
const group = new THREE.Group();
group.position.copy(position);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.7, 0.035, 4, 16),
new THREE.MeshBasicMaterial({
color: 0x70e6b4,
transparent: true,
opacity: 0.9
})
);
ring.rotation.x = Math.PI / 2;
group.add(ring);
const label = makeLabel("APEX", 0x70e6b4, 0.46);
label.position.set(0, 0.9, 0);
group.add(label);
const verticalGuide = makeDashedLine(
new THREE.Vector3(position.x, 0.03, position.z),
position.clone(),
0x70e6b4,
0.4
);
group.add(verticalGuide);
return group;
}
// ---------------------------------------------------------------------
// Rebuild all objects derived from the analytic path
// ---------------------------------------------------------------------
function rebuildTrajectory(resetTime = true) {
flightData = calculateFlight();
clearGroup(dynamicGroup);
const points = [];
for (let i = 0; i <= PATH_SAMPLES; i++) {
const time = flightData.impactTime * i / PATH_SAMPLES;
points.push(pointAtTime(flightData, time));
}
const trajectoryMesh = buildTrajectoryMesh(
points,
flightData.azimuth
);
dynamicGroup.add(trajectoryMesh);
const impactPosition = points[points.length - 1];
dynamicGroup.add(buildImpactMarker(impactPosition));
const apexPosition = pointAtTime(
flightData,
flightData.apexTime
);
dynamicGroup.add(buildApexMarker(apexPosition));
// Ground projection of the horizontal flight.
const groundProjection = makeDashedLine(
new THREE.Vector3(params.launchX, 0.035, params.launchZ),
new THREE.Vector3(impactPosition.x, 0.035, impactPosition.z),
0xffc46e,
0.5
);
dynamicGroup.add(groundProjection);
// Initial velocity vector.
const launchPosition = new THREE.Vector3(
params.launchX,
params.height,
params.launchZ
);
const velocityDirection = new THREE.Vector3(
flightData.vx,
flightData.vy,
flightData.vz
);
dynamicGroup.add(
makeArrow(
launchPosition,
velocityDirection,
4.8,
0xffdd73,
"v₀",
0.07,
0.55
)
);
updateLaunchMarker();
if (resetTime) {
simTime = 0;
impactHold = 0;
} else {
simTime = Math.min(simTime, flightData.impactTime);
}
projectile.position.copy(pointAtTime(flightData, simTime));
ui.flightTime.textContent = `${flightData.impactTime.toFixed(2)} s`;
ui.rangeValue.textContent = `${flightData.horizontalRange.toFixed(1)} m`;
ui.apexValue.textContent = `${flightData.apexY.toFixed(1)} m`;
ui.coordinates.textContent =
`r₀ = (${params.launchX.toFixed(1)}, ` +
`${params.height.toFixed(1)}, ${params.launchZ.toFixed(1)}) m`;
ui.timeScrub.value = String(
Math.round(simTime / flightData.impactTime * 1000)
);
}
// ---------------------------------------------------------------------
// UI events
// ---------------------------------------------------------------------
function updateControlLabels() {
ui.speedOut.textContent = `${params.speed.toFixed(1)} m/s`;
ui.elevationOut.textContent = `${params.elevation.toFixed(0)}°`;
ui.azimuthOut.textContent = `${params.azimuth.toFixed(0)}°`;
ui.heightOut.textContent = `${params.height.toFixed(1)} m`;
}
[
["speed", "speed"],
["elevation", "elevation"],
["azimuth", "azimuth"],
["height", "height"]
].forEach(([id, key]) => {
ui[id].addEventListener("input", () => {
params[key] = Number(ui[id].value);
updateControlLabels();
rebuildTrajectory(true);
});
});
function syncPlayButton() {
ui.playBtn.textContent = playing ? "❚❚ Pause motion" : "▶ Play motion";
ui.playBtn.classList.toggle("active", playing);
}
ui.playBtn.addEventListener("click", () => {
if (!playing && simTime >= flightData.impactTime - 0.001) {
simTime = 0;
impactHold = 0;
}
playing = !playing;
syncPlayButton();
});
ui.timeScrub.addEventListener("input", () => {
playing = false;
syncPlayButton();
simTime = flightData.impactTime * Number(ui.timeScrub.value) / 1000;
projectile.position.copy(pointAtTime(flightData, simTime));
});
ui.placeBtn.addEventListener("click", () => {
placementMode = !placementMode;
ui.placeBtn.classList.toggle("active", placementMode);
ui.placeBtn.textContent = placementMode
? "Click ground…"
: "⌖ Place launch";
showToast(
placementMode
? "Click a location on the ground plane."
: "Launch placement cancelled."
);
});
ui.resetBtn.addEventListener("click", () => {
params.launchX = INITIAL_LAUNCH.x;
params.launchZ = INITIAL_LAUNCH.z;
rebuildTrajectory(true);
showToast("Launch point reset.");
});
window.addEventListener("keydown", (event) => {
if (
event.code === "Space" &&
!["INPUT", "BUTTON"].includes(document.activeElement?.tagName)
) {
event.preventDefault();
ui.playBtn.click();
}
});
let toastTimer = 0;
function showToast(message) {
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => {
toast.classList.remove("visible");
}, 2200);
}
// ---------------------------------------------------------------------
// Direct camera controls: orbit, zoom, and pan
// ---------------------------------------------------------------------
const pointer = {
down: false,
button: 0,
startX: 0,
startY: 0,
lastX: 0,
lastY: 0,
moved: false,
placement: false
};
const raycaster = new THREE.Raycaster();
const pointerNDC = new THREE.Vector2();
renderer.domElement.addEventListener("pointerdown", (event) => {
pointer.down = true;
pointer.button = event.button;
pointer.startX = event.clientX;
pointer.startY = event.clientY;
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
pointer.moved = false;
pointer.placement = placementMode && event.button === 0;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointer.down) {
return;
}
const dx = event.clientX - pointer.lastX;
const dy = event.clientY - pointer.lastY;
const totalDistance = Math.hypot(
event.clientX - pointer.startX,
event.clientY - pointer.startY
);
if (totalDistance > 5) {
pointer.moved = true;
}
pointer.lastX = event.clientX;
pointer.lastY = event.clientY;
if (pointer.placement) {
return;
}
const panning = pointer.button === 2 || event.shiftKey;
if (panning) {
const forward = new THREE.Vector3();
camera.getWorldDirection(forward);
const right = new THREE.Vector3()
.crossVectors(forward, camera.up)
.normalize();
const up = new THREE.Vector3()
.crossVectors(right, forward)
.normalize();
const scale = cameraRadius * 0.0014;
cameraTarget.addScaledVector(right, -dx * scale);
cameraTarget.addScaledVector(up, dy * scale);
} else {
cameraTheta -= dx * 0.0055;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi + dy * 0.0045,
0.16,
Math.PI / 2 - 0.05
);
}
updateCamera();
});
function placeLaunchFromPointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointerNDC.set(
((event.clientX - rect.left) / rect.width) * 2 - 1,
-((event.clientY - rect.top) / rect.height) * 2 + 1
);
raycaster.setFromCamera(pointerNDC, camera);
const hit = raycaster.intersectObject(groundMesh, false)[0];
if (!hit) {
showToast("Click directly on the ground plane.");
return;
}
params.launchX = THREE.MathUtils.clamp(hit.point.x, -40, 40);
params.launchZ = THREE.MathUtils.clamp(hit.point.z, -40, 40);
placementMode = false;
ui.placeBtn.classList.remove("active");
ui.placeBtn.textContent = "⌖ Place launch";
rebuildTrajectory(true);
showToast("Launch point moved; trajectory recalculated.");
}
renderer.domElement.addEventListener("pointerup", (event) => {
if (pointer.placement && !pointer.moved) {
placeLaunchFromPointer(event);
}
pointer.down = false;
pointer.placement = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointer.down = false;
pointer.placement = false;
});
renderer.domElement.addEventListener("contextmenu", (event) => {
event.preventDefault();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
18,
115
);
updateCamera();
},
{ passive: false }
);
// ---------------------------------------------------------------------
// 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);
});
let previousTime = performance.now();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (playing && flightData) {
if (impactHold > 0) {
impactHold -= delta;
if (impactHold <= 0) {
simTime = 0;
}
} else {
simTime += delta;
if (simTime >= flightData.impactTime) {
simTime = flightData.impactTime;
impactHold = 0.65;
}
}
projectile.position.copy(pointAtTime(flightData, simTime));
ui.timeScrub.value = String(
Math.round(simTime / flightData.impactTime * 1000)
);
}
projectileBody.rotation.x += delta * 3.5;
projectileBody.rotation.y += delta * 5.0;
const launchPulse = 1 + Math.sin(now * 0.003) * 0.06;
launchHalo.scale.setScalar(launchPulse);
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
updateControlLabels();
rebuildTrajectory(true);
loading.style.opacity = "0";
setTimeout(() => {
loading.style.display = "none";
}, 260);
requestAnimationFrame(animate);
</script>
</body>
</html>
```