Prompt specification
Build or customize the Three.js 3D scene "Original Character Walks One Straight Segment" 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: Original Character Walks One Straight Segment
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/original-character-walks-one-straight-segment-x3758
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing walking cycles, foot contact, and stride length. Animate a stylized character walking along a short level path. Coordinate root movement with foot placement and keep a visible support foot during each stance phase. Voxel style.
Working Three.js Starter (original-character-walks-one-straight-segment-x3758):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Voxel Gait Lab</title>
<style>
:root {
--ink: #17313a;
--muted: #64777c;
--panel: rgba(248, 251, 249, 0.92);
--border: rgba(23, 49, 58, 0.13);
--green: #16a579;
--amber: #e59a3c;
--cyan: #159bb2;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #dbe7e8;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
#scene {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid var(--border);
background: var(--panel);
box-shadow: 0 14px 42px rgba(38, 68, 74, 0.14);
backdrop-filter: blur(14px);
-webkit-backdrop-filter: blur(14px);
}
#title-card {
top: 22px;
left: 22px;
width: min(390px, calc(100vw - 44px));
padding: 18px 20px 16px;
border-radius: 18px;
}
.eyebrow {
margin-bottom: 6px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(22px, 3vw, 31px);
line-height: 1.08;
letter-spacing: -0.035em;
}
.subtitle {
margin: 9px 0 0;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
#metrics {
top: 22px;
right: 22px;
width: 310px;
padding: 17px 18px;
border-radius: 18px;
}
.metrics-title {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 13px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
#support-state {
color: var(--green);
letter-spacing: 0.06em;
}
.foot-row {
display: grid;
grid-template-columns: 17px 56px 1fr;
align-items: center;
gap: 8px;
min-height: 34px;
font-size: 12px;
}
.dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 0 4px rgba(229, 154, 60, 0.13);
transition: background 100ms, box-shadow 100ms;
}
.foot-row.stance .dot {
background: var(--green);
box-shadow: 0 0 0 4px rgba(22, 165, 121, 0.15);
}
.foot-row > span:nth-child(2) {
font-weight: 800;
letter-spacing: 0.06em;
}
.foot-row strong {
justify-self: end;
color: var(--amber);
font-size: 10px;
letter-spacing: 0.08em;
}
.foot-row.stance strong {
color: var(--green);
}
.cycle-block {
margin-top: 11px;
padding-top: 11px;
border-top: 1px solid var(--border);
}
.cycle-row {
display: grid;
grid-template-columns: 18px 1fr;
align-items: center;
gap: 8px;
margin: 7px 0;
color: var(--muted);
font-size: 10px;
font-weight: 800;
}
.track {
position: relative;
height: 8px;
overflow: visible;
border-radius: 999px;
background: rgba(229, 154, 60, 0.5);
}
.track .stance-zone {
position: absolute;
inset: 0 auto 0 0;
width: 60%;
border-radius: 999px 0 0 999px;
background: var(--green);
}
.track i {
position: absolute;
top: 50%;
left: 0;
width: 3px;
height: 16px;
border-radius: 2px;
background: var(--ink);
transform: translate(-50%, -50%);
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.8);
}
.numbers {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
margin-top: 14px;
padding-top: 13px;
border-top: 1px solid var(--border);
}
.number {
min-width: 0;
}
.number span {
display: block;
margin-bottom: 3px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.number strong {
font-size: 14px;
white-space: nowrap;
}
#controls {
right: 22px;
bottom: 22px;
display: flex;
gap: 8px;
padding: 7px;
border-radius: 14px;
}
button {
appearance: none;
border: 0;
border-radius: 9px;
padding: 9px 12px;
background: #e7efed;
color: var(--ink);
font: inherit;
font-size: 11px;
font-weight: 800;
cursor: pointer;
transition: transform 120ms, background 120ms;
}
button:hover {
background: #d8e6e2;
transform: translateY(-1px);
}
button:active {
transform: translateY(0);
}
#legend {
left: 22px;
bottom: 22px;
display: flex;
flex-wrap: wrap;
gap: 13px;
align-items: center;
padding: 11px 14px;
border-radius: 14px;
color: var(--muted);
font-size: 10px;
font-weight: 700;
letter-spacing: 0.03em;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 50%;
}
.swatch.green {
background: var(--green);
}
.swatch.amber {
background: var(--amber);
}
.swatch.cyan {
background: var(--cyan);
}
.help {
color: #849396;
font-weight: 500;
}
.world-label,
.world-tag {
position: fixed;
z-index: 8;
pointer-events: none;
transform: translate(-50%, -50%);
white-space: nowrap;
}
.world-label {
padding: 6px 9px;
border: 1px solid rgba(21, 155, 178, 0.35);
border-radius: 8px;
background: rgba(236, 250, 251, 0.94);
color: #087f93;
box-shadow: 0 6px 18px rgba(20, 85, 95, 0.12);
font-size: 10px;
font-weight: 900;
letter-spacing: 0.08em;
}
.world-tag {
padding: 4px 7px;
border-radius: 6px;
background: rgba(16, 133, 101, 0.92);
color: white;
font-size: 9px;
font-weight: 900;
letter-spacing: 0.07em;
box-shadow: 0 5px 14px rgba(15, 98, 77, 0.18);
}
@media (max-width: 760px) {
#title-card {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
padding: 14px 16px;
}
.subtitle {
display: none;
}
#metrics {
top: auto;
right: 12px;
bottom: 66px;
width: 238px;
padding: 13px;
}
.numbers {
gap: 4px;
}
.number strong {
font-size: 12px;
}
#legend {
left: 12px;
bottom: 12px;
max-width: calc(100vw - 24px);
}
.help {
display: none;
}
#controls {
right: 12px;
top: 95px;
bottom: auto;
}
}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<section id="title-card" class="panel">
<div class="eyebrow">Biomechanics / Voxel Study</div>
<h1>Voxel Gait Lab</h1>
<p class="subtitle">
A world-space gait rig: planted feet remain fixed during stance, while the
pelvis advances over each support point.
</p>
</section>
<section id="metrics" class="panel">
<div class="metrics-title">
<span>Live Gait</span>
<span id="support-state">Double support</span>
</div>
<div id="right-row" class="foot-row">
<i class="dot"></i>
<span>RIGHT</span>
<strong id="right-state">STANCE</strong>
</div>
<div id="left-row" class="foot-row">
<i class="dot"></i>
<span>LEFT</span>
<strong id="left-state">SWING</strong>
</div>
<div class="cycle-block">
<div class="cycle-row">
<span>R</span>
<div class="track">
<div class="stance-zone"></div>
<i id="right-marker"></i>
</div>
</div>
<div class="cycle-row">
<span>L</span>
<div class="track">
<div class="stance-zone"></div>
<i id="left-marker"></i>
</div>
</div>
</div>
<div class="numbers">
<div class="number">
<span>Stride</span>
<strong>1.60 m</strong>
</div>
<div class="number">
<span>Step</span>
<strong>0.80 m</strong>
</div>
<div class="number">
<span>Speed</span>
<strong>1.33 m/s</strong>
</div>
</div>
</section>
<div id="legend" class="panel">
<div class="legend-item">
<i class="swatch green"></i>
Planted / support
</div>
<div class="legend-item">
<i class="swatch amber"></i>
Swing
</div>
<div class="legend-item">
<i class="swatch cyan"></i>
Same-foot stride
</div>
<div class="help">Drag to orbit · Wheel to zoom · Space to pause</div>
</div>
<div id="controls" class="panel">
<button id="pause-button" type="button">Pause</button>
<button id="camera-button" type="button">Reset view</button>
</div>
<div id="dimension-label" class="world-label">SAME-FOOT STRIDE · 1.60 m</div>
<div id="right-tag" class="world-tag">R · PLANTED</div>
<div id="left-tag" class="world-tag">L · PLANTED</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Gait constants
// -------------------------------------------------------------------------
const CYCLE_TIME = 1.20; // seconds for one full gait cycle
const STRIDE_LENGTH = 1.60; // distance between contacts of one foot
const STEP_LENGTH = STRIDE_LENGTH / 2;
const STANCE_FRACTION = 0.60; // overlap guarantees visible support
const WALK_SPEED = STRIDE_LENGTH / CYCLE_TIME;
const CONTACT_LEAD = 0.20; // foot is slightly ahead at contact
const ANKLE_HEIGHT = 0.23;
const START_X = -2.40;
const PATH_PERIOD = 6.00; // seamless local 6 m path segment
const TAU = Math.PI * 2;
const mod = (n, m) => ((n % m) + m) % m;
const lerp = THREE.MathUtils.lerp;
const clamp = THREE.MathUtils.clamp;
function smootherStep(t) {
t = clamp(t, 0, 1);
return t * t * t * (t * (t * 6 - 15) + 10);
}
// -------------------------------------------------------------------------
// Renderer, camera, lighting
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xdbe7e8);
scene.fog = new THREE.Fog(0xdbe7e8, 15, 38);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
100
);
const orbit = {
yaw: 0.31,
elevation: 0.34,
distance: 8.4
};
const hemisphere = new THREE.HemisphereLight(0xf4fbff, 0x6f8272, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff0cf, 3.2);
sun.position.set(4, 10, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -8;
sun.shadow.camera.right = 8;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.00015;
scene.add(sun);
scene.add(sun.target);
const fill = new THREE.DirectionalLight(0x9ddcf0, 0.85);
fill.position.set(-5, 4, -6);
scene.add(fill);
// -------------------------------------------------------------------------
// Materials and helper functions
// -------------------------------------------------------------------------
const materials = {
ground: new THREE.MeshStandardMaterial({ color: 0xbfd0ca, roughness: 1 }),
path: new THREE.MeshStandardMaterial({ color: 0xe4cba5, roughness: 0.95 }),
curb: new THREE.MeshStandardMaterial({ color: 0xf4efe3, roughness: 0.9 }),
tick: new THREE.MeshStandardMaterial({ color: 0x6f7b72, roughness: 0.9 }),
shirt: new THREE.MeshStandardMaterial({ color: 0xe6a83f, roughness: 0.82 }),
shirtDark: new THREE.MeshStandardMaterial({ color: 0xc57f2c, roughness: 0.88 }),
pants: new THREE.MeshStandardMaterial({ color: 0x294654, roughness: 0.88 }),
skin: new THREE.MeshStandardMaterial({ color: 0xe8b58c, roughness: 0.85 }),
hair: new THREE.MeshStandardMaterial({ color: 0x343239, roughness: 0.92 }),
black: new THREE.MeshStandardMaterial({ color: 0x18272d, roughness: 0.8 }),
backpack: new THREE.MeshStandardMaterial({ color: 0x2b7f78, roughness: 0.9 })
};
function makeBox(width, height, depth, material, parent, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// -------------------------------------------------------------------------
// Level walkway and ruler ticks
// -------------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(80, 50),
materials.ground
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.065;
ground.receiveShadow = true;
scene.add(ground);
const path = makeBox(60, 0.08, 2.80, materials.path, scene, 0, 0, 0);
path.receiveShadow = true;
makeBox(60, 0.12, 0.16, materials.curb, scene, 0, 0.015, 1.47);
makeBox(60, 0.12, 0.16, materials.curb, scene, 0, 0.015, -1.47);
const tickGeometry = new THREE.BoxGeometry(1, 1, 1);
const rulerTicks = [];
for (let i = 0; i < 90; i++) {
const tick = new THREE.Mesh(tickGeometry, materials.tick);
tick.receiveShadow = true;
scene.add(tick);
rulerTicks.push(tick);
}
function updateRuler(centerX) {
const spacing = 0.20;
const first = Math.floor((centerX - 9) / spacing) * spacing;
for (let i = 0; i < rulerTicks.length; i++) {
const x = first + i * spacing;
const tenth = Math.round(x * 10);
const isMeter = tenth % 10 === 0;
const isHalfMeter = tenth % 5 === 0;
rulerTicks[i].position.set(x, 0.055, 1.205);
rulerTicks[i].scale.set(
isMeter ? 0.045 : 0.025,
0.018,
isMeter ? 0.19 : isHalfMeter ? 0.13 : 0.075
);
}
}
// -------------------------------------------------------------------------
// Voxel character
// -------------------------------------------------------------------------
const character = new THREE.Group();
scene.add(character);
// Body model bobs, but feet remain attached to the ground-level root.
const body = new THREE.Group();
character.add(body);
makeBox(0.72, 0.28, 0.48, materials.pants, body, 0, 1.01, 0);
const chest = makeBox(0.62, 0.78, 0.44, materials.shirt, body, 0, 1.49, 0);
chest.rotation.z = -0.025;
makeBox(0.38, 0.58, 0.18, materials.backpack, body, -0.38, 1.48, 0);
makeBox(0.18, 0.13, 0.20, materials.skin, body, 0, 1.93, 0);
makeBox(0.56, 0.52, 0.52, materials.skin, body, 0, 2.18, 0);
makeBox(0.58, 0.12, 0.54, materials.hair, body, -0.015, 2.47, 0);
makeBox(0.12, 0.29, 0.54, materials.hair, body, -0.24, 2.24, 0);
// Face points toward +X, the direction of travel.
makeBox(0.035, 0.075, 0.075, materials.black, body, 0.286, 2.22, 0.125);
makeBox(0.035, 0.075, 0.075, materials.black, body, 0.286, 2.22, -0.125);
makeBox(0.11, 0.08, 0.10, materials.skin, body, 0.325, 2.12, 0);
const legLengthUpper = 0.58;
const legLengthLower = 0.58;
function createArm(z, materialColor) {
const pivot = new THREE.Group();
pivot.position.set(0, 1.72, z);
body.add(pivot);
const upperMaterial = new THREE.MeshStandardMaterial({
color: materialColor,
roughness: 0.84
});
makeBox(0.17, 0.34, 0.17, upperMaterial, pivot, 0, -0.17, 0);
const elbow = new THREE.Group();
elbow.position.y = -0.34;
pivot.add(elbow);
makeBox(0.15, 0.31, 0.15, upperMaterial, elbow, 0, -0.155, 0);
makeBox(0.17, 0.15, 0.17, materials.skin, elbow, 0, -0.36, 0);
return { pivot, elbow };
}
const rightArm = createArm(0.38, 0xe6a83f);
const leftArm = createArm(-0.38, 0xe6a83f);
function createFoot(sideName, z) {
const shoeMaterial = new THREE.MeshStandardMaterial({
color: 0x15916f,
emissive: 0x0b5f49,
emissiveIntensity: 0.42,
roughness: 0.72
});
const pivot = new THREE.Group();
character.add(pivot);
const shoe = makeBox(0.40, 0.16, 0.27, shoeMaterial, pivot, 0, -0.08, 0);
makeBox(0.42, 0.06, 0.29, materials.black, pivot, 0, -0.155, 0);
// Contact ring lies flat on the walkway.
const contactGroup = new THREE.Group();
character.add(contactGroup);
const ringMaterial = new THREE.MeshBasicMaterial({
color: 0x16c58f,
transparent: true,
opacity: 0.78,
depthWrite: false
});
const ring = new THREE.Mesh(
new THREE.TorusGeometry(0.265, 0.026, 7, 28),
ringMaterial
);
ring.rotation.x = Math.PI / 2;
contactGroup.add(ring);
const disc = new THREE.Mesh(
new THREE.CylinderGeometry(0.205, 0.205, 0.012, 24),
new THREE.MeshBasicMaterial({
color: 0x16c58f,
transparent: true,
opacity: 0.15,
depthWrite: false
})
);
contactGroup.add(disc);
return {
name: sideName,
z,
pivot,
shoe,
shoeMaterial,
contactGroup,
ringMaterial,
phase: 0,
stance: false,
localX: 0,
lift: 0,
contactX: 0
};
}
function createLeg(z) {
const upper = new THREE.Group();
upper.position.set(0, 0.98, z);
body.add(upper);
makeBox(
0.22,
legLengthUpper,
0.23,
materials.pants,
upper,
0,
-legLengthUpper / 2,
0
);
const lower = new THREE.Group();
lower.position.y = -legLengthUpper;
upper.add(lower);
makeBox(
0.19,
legLengthLower,
0.21,
materials.pants,
lower,
0,
-legLengthLower / 2,
0
);
makeBox(0.21, 0.12, 0.22, materials.hair, lower, 0, -legLengthLower + 0.03, 0);
return { upper, lower, hipY: 0.98, z };
}
const rightFoot = createFoot("RIGHT", 0.24);
const leftFoot = createFoot("LEFT", -0.24);
const rightLeg = createLeg(rightFoot.z);
const leftLeg = createLeg(leftFoot.z);
// Two-bone analytic IK for the voxel legs.
function solveLeg(leg, foot) {
const hipX = 0;
const hipY = leg.hipY;
const targetY = ANKLE_HEIGHT + foot.lift - body.position.y;
let dx = foot.localX - hipX;
let dy = targetY - hipY;
let distance = Math.hypot(dx, dy);
const maxReach = legLengthUpper + legLengthLower - 0.002;
if (distance > maxReach) {
const scale = maxReach / distance;
dx *= scale;
dy *= scale;
distance = maxReach;
}
const ux = dx / distance;
const uy = dy / distance;
const along = (
legLengthUpper * legLengthUpper -
legLengthLower * legLengthLower +
distance * distance
) / (2 * distance);
const bend = Math.sqrt(
Math.max(0, legLengthUpper * legLengthUpper - along * along)
);
// Always bends the knee forward in the direction of travel (+X).
const perpendicularX = -uy;
const perpendicularY = ux;
const kneeX = hipX + ux * along + perpendicularX * bend;
const kneeY = hipY + uy * along + perpendicularY * bend;
const upperAngle = Math.atan2(kneeX - hipX, -(kneeY - hipY));
const lowerAngle = Math.atan2(foot.localX - kneeX, -(targetY - kneeY));
leg.upper.rotation.z = upperAngle;
leg.lower.rotation.z = lowerAngle - upperAngle;
}
// -------------------------------------------------------------------------
// World-space stride dimension
// -------------------------------------------------------------------------
const dimensionGeometry = new THREE.BufferGeometry();
const dimensionPositions = new Float32Array(18);
dimensionGeometry.setAttribute(
"position",
new THREE.BufferAttribute(dimensionPositions, 3)
);
const dimensionMaterial = new THREE.LineBasicMaterial({
color: 0x159bb2,
transparent: true,
opacity: 0.9
});
const dimensionLine = new THREE.LineSegments(
dimensionGeometry,
dimensionMaterial
);
character.add(dimensionLine);
function updateDimension(startLocalX) {
const endLocalX = startLocalX + STRIDE_LENGTH;
const y = 0.075;
const z = 0.90;
const values = [
startLocalX, y, z,
endLocalX, y, z,
startLocalX, y, z - 0.11,
startLocalX, y, z + 0.11,
endLocalX, y, z - 0.11,
endLocalX, y, z + 0.11
];
dimensionGeometry.attributes.position.array.set(values);
dimensionGeometry.attributes.position.needsUpdate = true;
dimensionGeometry.computeBoundingSphere();
}
// -------------------------------------------------------------------------
// Gait calculation
// -------------------------------------------------------------------------
function rootAt(time) {
return START_X + WALK_SPEED * time;
}
function calculateFoot(offset, foot) {
const gaitU = elapsed / CYCLE_TIME;
const phase = mod(gaitU + offset, 1);
const cycleIndex = Math.floor(gaitU + offset);
const contactTime = (cycleIndex - offset) * CYCLE_TIME;
const contactX = rootAt(contactTime) + CONTACT_LEAD;
const stance = phase < STANCE_FRACTION;
let localX;
let lift = 0;
if (stance) {
/*
* A planted foot has a fixed WORLD contact point. Since the root moves,
* its local offset changes by exactly the negative of root travel.
*/
localX = contactX - rootAt(elapsed);
} else {
const swingProgress = (phase - STANCE_FRACTION) / (1 - STANCE_FRACTION);
const eased = smootherStep(swingProgress);
const liftOffsetAtStart =
CONTACT_LEAD - WALK_SPEED * CYCLE_TIME * STANCE_FRACTION;
const localAtLanding = CONTACT_LEAD;
localX = lerp(liftOffsetAtStart, localAtLanding, eased);
lift = Math.sin(Math.PI * swingProgress) * 0.31;
}
foot.phase = phase;
foot.stance = stance;
foot.localX = localX;
foot.lift = lift;
foot.contactX = contactX;
foot.pivot.position.set(
localX,
ANKLE_HEIGHT + lift,
foot.z
);
const toeLift = stance
? 0
: Math.sin(
Math.PI *
((phase - STANCE_FRACTION) / (1 - STANCE_FRACTION))
) * 0.17;
foot.pivot.rotation.z = toeLift;
if (stance) {
foot.shoeMaterial.color.setHex(0x15916f);
foot.shoeMaterial.emissive.setHex(0x075a45);
foot.shoeMaterial.emissiveIntensity = 0.50;
foot.contactGroup.visible = true;
foot.contactGroup.position.set(localX, 0.061, foot.z);
const pulse = phase < 0.08
? 1 + 0.12 * (1 - phase / 0.08)
: 1;
foot.contactGroup.scale.setScalar(pulse);
foot.ringMaterial.opacity = 0.78;
} else {
foot.shoeMaterial.color.setHex(0xd58a38);
foot.shoeMaterial.emissive.setHex(0x8d4711);
foot.shoeMaterial.emissiveIntensity = 0.24;
foot.contactGroup.visible = false;
}
}
// -------------------------------------------------------------------------
// HUD
// -------------------------------------------------------------------------
const rightStateEl = document.querySelector("#right-state");
const leftStateEl = document.querySelector("#left-state");
const rightRowEl = document.querySelector("#right-row");
const leftRowEl = document.querySelector("#left-row");
const supportStateEl = document.querySelector("#support-state");
const rightMarkerEl = document.querySelector("#right-marker");
const leftMarkerEl = document.querySelector("#left-marker");
const dimensionLabelEl = document.querySelector("#dimension-label");
const rightTagEl = document.querySelector("#right-tag");
const leftTagEl = document.querySelector("#left-tag");
function setFootHUD(foot, stateEl, rowEl, markerEl) {
stateEl.textContent = foot.stance ? "STANCE / SUPPORT" : "SWING";
rowEl.classList.toggle("stance", foot.stance);
markerEl.style.left = `${foot.phase * 100}%`;
}
function projectToScreen(worldPosition) {
const projected = worldPosition.clone().project(camera);
const visible =
projected.z >= -1 &&
projected.z <= 1 &&
Math.abs(projected.x) < 1.15 &&
Math.abs(projected.y) < 1.15;
return {
visible,
x: (projected.x * 0.5 + 0.5) * window.innerWidth,
y: (-projected.y * 0.5 + 0.5) * window.innerHeight
};
}
function positionTag(element, foot, visible) {
if (!visible || !foot.stance) {
element.style.display = "none";
return;
}
const worldPosition = new THREE.Vector3(
character.position.x + foot.localX,
0.66,
foot.z + 0.08
);
const screen = projectToScreen(worldPosition);
if (!screen.visible) {
element.style.display = "none";
return;
}
element.style.display = "block";
element.style.left = `${screen.x}px`;
element.style.top = `${screen.y}px`;
}
// -------------------------------------------------------------------------
// Camera controls, implemented directly without external addons
// -------------------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
orbit.yaw -= dx * 0.006;
orbit.elevation = clamp(orbit.elevation + dy * 0.004, 0.12, 0.82);
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.distance = clamp(
orbit.distance * Math.exp(event.deltaY * 0.001),
4.2,
15
);
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
function resetCamera() {
orbit.yaw = 0.31;
orbit.elevation = 0.34;
orbit.distance = 8.4;
}
// -------------------------------------------------------------------------
// Animation state
// -------------------------------------------------------------------------
let elapsed = 0;
let paused = false;
const pauseButton = document.querySelector("#pause-button");
const cameraButton = document.querySelector("#camera-button");
function togglePause() {
paused = !paused;
pauseButton.textContent = paused ? "Resume" : "Pause";
}
pauseButton.addEventListener("click", togglePause);
cameraButton.addEventListener("click", resetCamera);
window.addEventListener("keydown", (event) => {
if (event.code === "Space" && event.target === document.body) {
event.preventDefault();
togglePause();
}
if (event.key.toLowerCase() === "r") {
resetCamera();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
let previousTime = performance.now();
renderer.setAnimationLoop((time) => {
const dt = Math.min((time - previousTime) / 1000, 0.05);
previousTime = time;
if (!paused) {
elapsed += dt;
}
const unwrappedRootX = rootAt(elapsed);
/*
* The camera follows a repeating 6 m section. The ruler is periodic and
* its spacing divides the section length, so the visual wrap is seamless.
*/
const wrappedRootX =
START_X + mod(unwrappedRootX - START_X, PATH_PERIOD);
character.position.x = wrappedRootX;
updateRuler(wrappedRootX);
calculateFoot(0, rightFoot);
calculateFoot(0.5, leftFoot);
// Two vertical oscillations per full gait cycle.
body.position.y = -0.025 * Math.cos(4 * Math.PI * elapsed / CYCLE_TIME);
// Arms counter-rotate with the opposite legs.
rightArm.pivot.rotation.z = -0.34 * Math.cos(TAU * rightFoot.phase);
leftArm.pivot.rotation.z = -0.34 * Math.cos(TAU * leftFoot.phase);
rightArm.elbow.rotation.z = 0.12 + 0.10 * Math.max(0, rightArm.pivot.rotation.z);
leftArm.elbow.rotation.z = 0.12 + 0.10 * Math.max(0, leftArm.pivot.rotation.z);
solveLeg(rightLeg, rightFoot);
solveLeg(leftLeg, leftFoot);
// The dimension joins two consecutive contacts of the same right foot.
const strideStartLocal = rightFoot.contactX - unwrappedRootX;
updateDimension(strideStartLocal);
// Camera target follows the character along the level path.
const target = new THREE.Vector3(
wrappedRootX + 0.30,
1.05,
0
);
const horizontalDistance =
Math.cos(orbit.elevation) * orbit.distance;
camera.position.set(
target.x + Math.sin(orbit.yaw) * horizontalDistance,
target.y + Math.sin(orbit.elevation) * orbit.distance,
target.z + Math.cos(orbit.yaw) * horizontalDistance
);
camera.lookAt(target);
camera.updateMatrixWorld();
sun.position.set(wrappedRootX + 4, 10, 6);
sun.target.position.set(wrappedRootX, 0, 0);
setFootHUD(rightFoot, rightStateEl, rightRowEl, rightMarkerEl);
setFootHUD(leftFoot, leftStateEl, leftRowEl, leftMarkerEl);
if (rightFoot.stance && leftFoot.stance) {
supportStateEl.textContent = "Double support";
} else if (rightFoot.stance) {
supportStateEl.textContent = "Right support";
} else {
supportStateEl.textContent = "Left support";
}
const dimensionWorld = new THREE.Vector3(
wrappedRootX + strideStartLocal + STRIDE_LENGTH / 2,
0.18,
0.90
);
const dimensionScreen = projectToScreen(dimensionWorld);
dimensionLabelEl.style.display = dimensionScreen.visible ? "block" : "none";
dimensionLabelEl.style.left = `${dimensionScreen.x}px`;
dimensionLabelEl.style.top = `${dimensionScreen.y}px`;
positionTag(rightTagEl, rightFoot, dimensionScreen.visible);
positionTag(leftTagEl, leftFoot, dimensionScreen.visible);
renderer.render(scene, camera);
});
</script>
</body>
</html>
```