Prompt specification
Build or customize the Three.js 3D scene "Market Errand Walking Scene" 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: Market Errand Walking Scene
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/market-errand-walking-scene-x3759
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring walking cycles, foot contact, and stride length. Build a compact original market where a character walks, stops, turns, and resumes. Match gait transitions to speed and prevent intersection with stalls or baskets. Voxel style.
Working Three.js Starter (market-errand-walking-scene-x3759):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Bramblewick Voxel Market</title>
<style>
:root {
color-scheme: light;
--ink: #20313a;
--paper: #fff8e9;
--accent: #e76f51;
--mint: #3a9d8f;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #c9e4e4;
font-family: ui-rounded, "Trebuchet MS", system-ui, sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
#hud {
position: fixed;
inset: 18px 18px auto 18px;
z-index: 5;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
pointer-events: none;
}
.card {
border: 2px solid rgba(32, 49, 58, .16);
background: rgba(255, 248, 233, .9);
box-shadow: 0 9px 28px rgba(49, 67, 68, .13);
backdrop-filter: blur(9px);
border-radius: 16px;
}
#title {
padding: 13px 16px 12px;
max-width: 430px;
}
#title h1 {
margin: 0;
color: var(--ink);
font-size: clamp(18px, 2.1vw, 28px);
letter-spacing: .08em;
line-height: 1;
}
#title p {
margin: 7px 0 0;
color: #587078;
font-size: 12px;
line-height: 1.35;
}
#telemetry {
min-width: 220px;
padding: 12px 14px;
pointer-events: auto;
}
.row {
display: flex;
justify-content: space-between;
gap: 18px;
margin: 4px 0;
font-size: 12px;
color: #52666d;
}
.row strong {
color: var(--ink);
font-variant-numeric: tabular-nums;
}
#state {
color: var(--accent);
letter-spacing: .12em;
font-weight: 900;
}
#progressTrack {
height: 6px;
margin-top: 10px;
overflow: hidden;
border-radius: 99px;
background: #d9ded3;
}
#progress {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--mint), #efb44d);
transition: width .2s ease;
}
#contacts {
display: flex;
gap: 7px;
align-items: center;
margin-top: 9px;
color: #64767b;
font-size: 11px;
}
.contact {
width: 10px;
height: 10px;
border-radius: 3px;
background: #b8c2bc;
box-shadow: inset 0 0 0 1px rgba(0,0,0,.08);
transition: background .08s linear;
}
.contact.on { background: var(--mint); }
#replay {
margin-top: 10px;
width: 100%;
border: 0;
border-radius: 9px;
padding: 8px 10px;
color: white;
background: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 800;
cursor: pointer;
}
#replay:hover { background: #34515a; }
#help {
position: fixed;
left: 18px;
bottom: 18px;
z-index: 5;
padding: 9px 12px;
color: #53686f;
font-size: 11px;
pointer-events: none;
}
#error {
position: fixed;
inset: 0;
z-index: 20;
display: none;
place-items: center;
padding: 30px;
background: #f7ead3;
color: #283c43;
text-align: center;
font-weight: 700;
}
@media (max-width: 700px) {
#hud { inset: 10px 10px auto 10px; }
#title p { display: none; }
#title { padding: 11px 13px; }
#telemetry { min-width: 178px; padding: 10px; }
#help { left: 10px; bottom: 10px; }
}
</style>
</head>
<body>
<div id="hud">
<section id="title" class="card">
<h1>BRAMBLEWICK MARKET</h1>
<p>A tiny voxel market with planted-foot walking, measured strides, smooth stops and in-place turns.</p>
</section>
<section id="telemetry" class="card" aria-live="polite">
<div class="row"><span id="state">READY</span><strong id="speed">0.00 m/s</strong></div>
<div class="row"><span>Full stride</span><strong>0.72 m</strong></div>
<div class="row"><span>Body radius</span><strong>0.24 m</strong></div>
<div id="contacts">
<span class="contact on" id="leftContact"></span>
<span class="contact on" id="rightContact"></span>
<span>ground contact</span>
</div>
<div id="progressTrack"><div id="progress"></div></div>
<button id="replay" type="button">Replay market route</button>
</section>
</div>
<div id="help" class="card">Drag to orbit · Wheel to zoom · Double-click to reset camera</div>
<div id="error">WebGL could not be initialized. Please use a browser with WebGL enabled.</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Scene
// -------------------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xc9e4e4);
scene.fog = new THREE.Fog(0xc9e4e4, 15, 27);
let renderer;
try {
renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: "high-performance" });
} catch (error) {
document.getElementById("error").style.display = "grid";
throw error;
}
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
document.body.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(43, innerWidth / innerHeight, 0.1, 60);
scene.add(new THREE.HemisphereLight(0xeafaff, 0x8d765b, 2.25));
const sun = new THREE.DirectionalLight(0xfff0cf, 3.2);
sun.position.set(7, 11, 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 = 1;
sun.shadow.camera.far = 28;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x98cdd7, 0.8);
fill.position.set(-6, 5, -5);
scene.add(fill);
const materialCache = new Map();
function material(color, roughness = 0.82) {
const key = `${color}-${roughness}`;
if (!materialCache.has(key)) {
materialCache.set(key, new THREE.MeshStandardMaterial({
color,
roughness,
metalness: 0,
flatShading: true
}));
}
return materialCache.get(key);
}
function box(w, h, d, color, x = 0, y = 0, z = 0, parent = scene) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), material(color));
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function smooth01(t) {
t = THREE.MathUtils.clamp(t, 0, 1);
return t * t * (3 - 2 * t);
}
// -------------------------------------------------------------------------
// Ground and paving
// -------------------------------------------------------------------------
box(9.4, 0.28, 7.5, 0x8f8065, 0, -0.19, 0);
const tileGeo = new THREE.BoxGeometry(0.69, 0.065, 0.69);
const tileMat = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.94,
flatShading: true
});
const tileCount = 12 * 9;
const tiles = new THREE.InstancedMesh(tileGeo, tileMat, tileCount);
tiles.receiveShadow = true;
const dummy = new THREE.Object3D();
const tileColors = [0xe8dcc2, 0xd9d1bd, 0xeee3cc, 0xcfc8b6];
let tileIndex = 0;
for (let z = 0; z < 9; z++) {
for (let x = 0; x < 12; x++) {
dummy.position.set((x - 5.5) * 0.72, -0.015, (z - 4) * 0.72);
dummy.rotation.y = ((x + z) % 2) * 0.012;
dummy.updateMatrix();
tiles.setMatrixAt(tileIndex, dummy.matrix);
tiles.setColorAt(tileIndex, new THREE.Color(tileColors[(x * 3 + z) % tileColors.length]));
tileIndex++;
}
}
tiles.instanceMatrix.needsUpdate = true;
tiles.instanceColor.needsUpdate = true;
scene.add(tiles);
// A painted central aisle.
for (let i = 0; i < 14; i++) {
box(0.08, 0.012, 0.30, 0xf3ead4, -1.6, 0.026, -2.45 + i * 0.47);
box(0.08, 0.012, 0.30, 0xf3ead4, 1.28, 0.026, -2.45 + i * 0.47);
}
// -------------------------------------------------------------------------
// Collision geometry
// -------------------------------------------------------------------------
const BODY_RADIUS = 0.24;
const obstacles = [];
function addObstacle(x, z, halfX, halfZ, label) {
obstacles.push({ x, z, halfX, halfZ, label });
}
function pointHitsObstacle(x, z, obstacle) {
const closestX = THREE.MathUtils.clamp(x, obstacle.x - obstacle.halfX, obstacle.x + obstacle.halfX);
const closestZ = THREE.MathUtils.clamp(z, obstacle.z - obstacle.halfZ, obstacle.z + obstacle.halfZ);
const dx = x - closestX;
const dz = z - closestZ;
return dx * dx + dz * dz < BODY_RADIUS * BODY_RADIUS;
}
function blocked(x, z) {
for (const obstacle of obstacles) {
if (pointHitsObstacle(x, z, obstacle)) return obstacle;
}
return null;
}
// -------------------------------------------------------------------------
// Voxel market construction
// -------------------------------------------------------------------------
function makeSignTexture(title, subtitle, background, foreground) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 192;
const ctx = canvas.getContext("2d");
ctx.fillStyle = background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = foreground;
ctx.lineWidth = 12;
ctx.strokeRect(10, 10, canvas.width - 20, canvas.height - 20);
ctx.textAlign = "center";
ctx.fillStyle = foreground;
ctx.font = "900 48px Trebuchet MS, sans-serif";
ctx.fillText(title, 256, 79);
ctx.globalAlpha = 0.82;
ctx.font = "700 23px Trebuchet MS, sans-serif";
ctx.fillText(subtitle, 256, 126);
ctx.globalAlpha = 0.55;
ctx.font = "700 18px Trebuchet MS, sans-serif";
ctx.fillText("BRAMBLEWICK · EST. 1842", 256, 163);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
return texture;
}
function makeStall({
x, z, yaw = 0, width = 1.8, depth = 1.08,
awning, accent, title, subtitle, goods
}) {
const group = new THREE.Group();
group.position.set(x, 0, z);
group.rotation.y = yaw;
scene.add(group);
// Counter and legs.
box(width, 0.22, depth * 0.72, 0x9b6846, 0, 0.71, 0, group);
box(width - 0.12, 0.36, depth * 0.62, 0xb47b50, 0, 0.45, 0, group);
for (const sx of [-1, 1]) {
for (const sz of [-1, 1]) {
box(0.13, 0.72, 0.13, 0x644936,
sx * (width * 0.5 - 0.12), 0.35,
sz * (depth * 0.27), group);
}
}
// Back wall and canopy posts.
box(width, 0.95, 0.12, accent, 0, 1.15, -depth * 0.43, group);
for (const sx of [-1, 1]) {
box(0.11, 1.28, 0.11, 0x604b3a,
sx * (width * 0.5 - 0.10), 1.18,
depth * 0.40, group);
}
// Striped voxel awning.
const stripeCount = 6;
const stripeWidth = width / stripeCount;
for (let i = 0; i < stripeCount; i++) {
const stripeColor = i % 2 === 0 ? awning : 0xf5e6c8;
box(stripeWidth + 0.012, 0.17, depth * 1.13,
stripeColor,
-width * 0.5 + stripeWidth * (i + 0.5),
1.83, 0, group);
}
box(width + 0.08, 0.12, depth * 1.16, 0x76543c, 0, 1.91, 0, group);
// Produce arranged as tiny cubes.
for (let i = 0; i < goods.length; i++) {
const gx = (i % 4 - 1.5) * width * 0.19;
const gz = (Math.floor(i / 4) % 2 - 0.5) * depth * 0.23;
const size = 0.13 + ((i * 7) % 3) * 0.018;
box(size, size, size, goods[i], gx, 0.91 + size * 0.5, gz, group);
}
// Front sign.
const signTexture = makeSignTexture(title, subtitle, `#${accent.toString(16).padStart(6, "0")}`, "#fff8e9");
const signMaterial = new THREE.MeshBasicMaterial({ map: signTexture, side: THREE.DoubleSide });
const sign = new THREE.Mesh(new THREE.PlaneGeometry(width * 0.82, width * 0.31), signMaterial);
sign.position.set(0, 1.48, depth * 0.45 + 0.012);
group.add(sign);
// World-axis footprint, accounting for a 90-degree stall rotation.
const sideStall = Math.abs(Math.sin(yaw)) > 0.5;
const halfX = sideStall ? depth * 0.5 : width * 0.5;
const halfZ = sideStall ? width * 0.5 : depth * 0.5;
addObstacle(x, z, halfX, halfZ, title);
return group;
}
makeStall({
x: -3.25, z: 0.30, yaw: Math.PI / 2,
awning: 0x4d9c8f, accent: 0x28766f,
title: "MOSS & MINT", subtitle: "HERBS · LEAVES · TINY TEA",
goods: [0x83c957, 0x3d8d67, 0xb7df70, 0xe3b84d]
});
makeStall({
x: 3.25, z: 0.30, yaw: -Math.PI / 2,
awning: 0xef9850, accent: 0xb85c3d,
title: "SUN ORCHARD", subtitle: "PEACHES · PLUMS · SUNSHINE",
goods: [0xf2a34b, 0xd65f55, 0xe9c55c, 0x9f593d]
});
makeStall({
x: -1.65, z: 2.72, yaw: Math.PI,
awning: 0xd96355, accent: 0x8f3e3a,
title: "ROOT & RYE", subtitle: "BREAD · ROOTS · HONEY",
goods: [0xd69a4b, 0xe0bd6f, 0x8ca05c, 0xb9543f]
});
makeStall({
x: 1.55, z: 2.72, yaw: Math.PI,
awning: 0xe4b64c, accent: 0xa97830,
title: "PIXEL BREAD", subtitle: "CRUSTY LOAVES · DAILY",
goods: [0xe5b75d, 0xf0cf87, 0xbf803b, 0xdda34a]
});
makeStall({
x: -3.18, z: -2.30, yaw: 0,
awning: 0x8a74b5, accent: 0x554777,
title: "MOON TEA", subtitle: "PETALS · PEPPERMINT · DREAMS",
goods: [0xb486bd, 0xd8a6cf, 0x78a57a, 0xe7c08b]
});
makeStall({
x: 3.18, z: -2.30, yaw: 0,
awning: 0x68a764, accent: 0x397247,
title: "GLOW BERRIES", subtitle: "PICKED THIS MORNING",
goods: [0xb74e63, 0xdb6870, 0x7f4c85, 0xe18178]
});
function makeBasket(x, z, color = 0xa96f43) {
const group = new THREE.Group();
group.position.set(x, 0, z);
scene.add(group);
box(0.43, 0.09, 0.43, 0x6f4b35, 0, 0.045, 0, group);
const pieces = [
[-0.17, -0.17], [0, -0.19], [0.17, -0.17],
[-0.19, 0], [0.19, 0],
[-0.17, 0.17], [0, 0.19], [0.17, 0.17]
];
for (let layer = 0; layer < 4; layer++) {
const y = 0.13 + layer * 0.105;
const inset = layer === 3 ? 0.018 : 0;
for (const [px, pz] of pieces) {
box(0.115, 0.105, 0.115, color,
px * (1 - inset), y, pz * (1 - inset), group);
}
}
const fruit = [0xe3694f, 0xe5ae48, 0x7da35b][Math.abs(Math.round(x * 10 + z * 7)) % 3];
box(0.18, 0.15, 0.18, fruit, 0, 0.57, 0, group);
addObstacle(x, z, 0.25, 0.25, "basket");
}
makeBasket(-0.30, -3.17, 0xb47a4d);
makeBasket(0.38, -3.17, 0x9e693f);
makeBasket(-2.52, 1.62, 0xc18a54);
makeBasket(2.65, 1.62, 0xa97043);
function makeTree(x, z, crown = 0x5b9563) {
box(0.34, 1.65, 0.34, 0x75513b, x, 0.82, z);
box(1.05, 0.75, 1.00, crown, x, 1.78, z);
box(0.78, 0.68, 0.90, 0x6ca86c, x - 0.42, 1.55, z + 0.06);
box(0.75, 0.62, 0.72, 0x4f8758, x + 0.38, 1.63, z - 0.06);
}
makeTree(-4.12, 3.05, 0x5f9567);
makeTree(4.08, 3.05, 0x568d62);
makeTree(-4.10, -3.05, 0x6a9c65);
makeTree(4.08, -3.05, 0x5b8e63);
function makeLamp(x, z) {
box(0.12, 2.2, 0.12, 0x40545a, x, 1.1, z);
box(0.36, 0.12, 0.36, 0x40545a, x, 2.18, z);
box(0.25, 0.28, 0.25, 0xffe4a3, x, 2.02, z);
box(0.42, 0.10, 0.42, 0x40545a, x, 1.85, z);
}
makeLamp(-2.62, -3.08);
makeLamp(2.72, -3.08);
// Low perimeter planters.
for (const x of [-2.0, 0, 2.0]) {
box(0.80, 0.35, 0.48, 0x9b6b49, x, 0.18, 3.42);
for (let i = 0; i < 5; i++) {
box(0.23, 0.25 + (i % 2) * 0.12, 0.25,
i % 2 ? 0x83b765 : 0x5e9563,
x - 0.28 + i * 0.14, 0.45 + (i % 2) * 0.06, 3.42);
}
}
// -------------------------------------------------------------------------
// Character
// -------------------------------------------------------------------------
const STRIDE = 0.72;
const FOOT_LEAD = 0.10;
const FOOT_SIDE = 0.15;
const START_POSITION = new THREE.Vector3(-1.60, 0, -2.40);
const rootPosition = START_POSITION.clone();
let heading = 0;
let currentSpeed = 0;
const actor = new THREE.Group();
scene.add(actor);
const bodyPivot = new THREE.Group();
actor.add(bodyPivot);
// Torso, hips, head and accessories.
box(0.43, 0.22, 0.29, 0x324b57, 0, 0.80, 0, bodyPivot);
box(0.49, 0.58, 0.30, 0x397b83, 0, 1.17, 0, bodyPivot);
box(0.51, 0.12, 0.32, 0xf0c85d, 0, 1.47, 0, bodyPivot);
box(0.41, 0.41, 0.39, 0xe7b38d, 0, 1.69, 0.015, bodyPivot);
box(0.44, 0.13, 0.43, 0x4a3531, 0, 1.90, 0, bodyPivot);
box(0.46, 0.12, 0.17, 0x3d6c73, 0, 1.96, 0.13, bodyPivot);
// Eyes, nose, cheeks and scarf.
box(0.052, 0.062, 0.027, 0x263238, -0.09, 1.72, 0.216, bodyPivot);
box(0.052, 0.062, 0.027, 0x263238, 0.09, 1.72, 0.216, bodyPivot);
box(0.065, 0.065, 0.065, 0xd39777, 0, 1.64, 0.235, bodyPivot);
box(0.07, 0.04, 0.025, 0xe59d85, -0.14, 1.61, 0.205, bodyPivot);
box(0.07, 0.04, 0.025, 0xe59d85, 0.14, 1.61, 0.205, bodyPivot);
box(0.50, 0.11, 0.34, 0xe46d53, 0, 1.52, 0, bodyPivot);
// Backpack.
box(0.36, 0.42, 0.18, 0xb26b45, 0, 1.17, -0.23, bodyPivot);
box(0.26, 0.12, 0.06, 0xe0a260, 0, 1.16, -0.34, bodyPivot);
// Boots are world-space so they can remain planted during the stance phase.
function makeFoot() {
const foot = new THREE.Mesh(
new THREE.BoxGeometry(0.20, 0.12, 0.30),
material(0x30383d)
);
foot.castShadow = true;
foot.receiveShadow = true;
scene.add(foot);
return foot;
}
function makeSegment(width, depth, color) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, 1, depth),
material(color)
);
mesh.castShadow = true;
scene.add(mesh);
return mesh;
}
const feet = [
{
name: "left",
side: -FOOT_SIDE,
mesh: makeFoot(),
anchor: new THREE.Vector3(),
target: new THREE.Vector3(),
swingStart: new THREE.Vector3(),
swinging: false,
startU: 0
},
{
name: "right",
side: FOOT_SIDE,
mesh: makeFoot(),
anchor: new THREE.Vector3(),
target: new THREE.Vector3(),
swingStart: new THREE.Vector3(),
swinging: false,
startU: 0
}
];
const legs = feet.map(() => ({
upper: makeSegment(0.16, 0.16, 0x40566c),
lower: makeSegment(0.14, 0.14, 0x354754)
}));
const arms = [-1, 1].map(side => ({
side,
upper: makeSegment(0.13, 0.14, 0x397b83),
lower: makeSegment(0.12, 0.13, 0xe7b38d),
hand: new THREE.Mesh(new THREE.BoxGeometry(0.14, 0.14, 0.14), material(0xe7b38d))
}));
arms.forEach(arm => {
arm.hand.castShadow = true;
scene.add(arm.hand);
});
function forwardVector(yaw = heading) {
return new THREE.Vector3(Math.sin(yaw), 0, Math.cos(yaw));
}
function rightVector(yaw = heading) {
return new THREE.Vector3(Math.cos(yaw), 0, -Math.sin(yaw));
}
function initializeFeet() {
const forward = forwardVector(0);
const right = rightVector(0);
feet[0].anchor.copy(rootPosition)
.addScaledVector(forward, FOOT_LEAD)
.addScaledVector(right, feet[0].side);
feet[1].anchor.copy(rootPosition)
.addScaledVector(forward, -FOOT_LEAD)
.addScaledVector(right, feet[1].side);
feet.forEach(foot => {
foot.swinging = false;
foot.mesh.position.copy(foot.anchor);
foot.mesh.position.y = 0.065;
});
}
initializeFeet();
const Y_AXIS = new THREE.Vector3(0, 1, 0);
function setSegment(mesh, from, to) {
const delta = new THREE.Vector3().subVectors(to, from);
const length = Math.max(0.0001, delta.length());
const direction = delta.clone().divideScalar(length);
mesh.position.copy(from).add(to).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(Y_AXIS, direction);
mesh.scale.set(1, length, 1);
}
function updateTwoBone(start, end, lengthA, lengthB, bendDirection, upper, lower) {
const delta = new THREE.Vector3().subVectors(end, start);
const distance = THREE.MathUtils.clamp(delta.length(), 0.001, lengthA + lengthB - 0.001);
const direction = delta.clone().normalize();
const along = (lengthA * lengthA - lengthB * lengthB + distance * distance) / (2 * distance);
const height = Math.sqrt(Math.max(0, lengthA * lengthA - along * along));
let bend = bendDirection.clone().addScaledVector(direction, -bendDirection.dot(direction));
if (bend.lengthSq() < 0.0001) bend.set(0, 0, 1);
bend.normalize();
const joint = start.clone()
.addScaledVector(direction, along)
.addScaledVector(bend, height);
setSegment(upper, start, joint);
setSegment(lower, joint, end);
return joint;
}
// -------------------------------------------------------------------------
// Motion controller
//
// Gait phase is driven by actual distance, not frame time. Each foot remains
// fixed in world space during stance. Swing targets are predicted from the
// exact remaining half-stride, so acceleration does not cause foot sliding.
// -------------------------------------------------------------------------
let gaitU = 0;
let nextBoundary = 0.5;
function beginSwing(foot, boundaryRoot, direction) {
foot.swinging = true;
foot.startU = boundaryRoot.distanceTo(rootPosition) / STRIDE;
foot.swingStart.copy(foot.anchor);
foot.target.copy(boundaryRoot)
.addScaledVector(direction, STRIDE * 0.5 + FOOT_LEAD)
.addScaledVector(rightVector(), foot.side);
}
function landFoot(foot) {
if (foot.swinging) {
foot.anchor.copy(foot.target);
foot.swinging = false;
}
}
function updateGait(actualDistance, movementStart, direction) {
const oldU = gaitU;
const newU = gaitU + actualDistance / STRIDE;
gaitU = newU;
while (nextBoundary <= newU + 1e-8) {
const boundaryRoot = movementStart.clone().addScaledVector(direction, nextBoundary * STRIDE);
if (Math.abs((nextBoundary % 1) - 0.5) < 1e-6) {
// Right foot lands; left foot begins its swing.
landFoot(feet[1]);
beginSwing(feet[0], boundaryRoot, direction);
} else {
// Left foot lands; right foot begins the next swing.
landFoot(feet[0]);
beginSwing(feet[1], boundaryRoot, direction);
}
nextBoundary += 0.5;
}
}
function rotateAnchorAroundRoot(anchor, deltaYaw) {
const offset = anchor.clone().sub(rootPosition);
const c = Math.cos(deltaYaw);
const s = Math.sin(deltaYaw);
const x = c * offset.x + s * offset.z;
const z = -s * offset.x + c * offset.z;
anchor.set(rootPosition.x + x, anchor.y, rootPosition.z + z);
}
function moveWithCollision(dx, dz) {
const steps = Math.max(1, Math.ceil(Math.hypot(dx, dz) / 0.035));
const sx = dx / steps;
const sz = dz / steps;
let moved = 0;
for (let i = 0; i < steps; i++) {
const nx = rootPosition.x + sx;
const nz = rootPosition.z + sz;
if (!blocked(nx, nz)) {
rootPosition.x = nx;
rootPosition.z = nz;
moved += Math.hypot(sx, sz);
} else {
// Conservative stop rather than allowing a body/stall intersection.
break;
}
}
return moved;
}
function makeProfile(length, requestedSpeed, acceleration = 3.4, deceleration = 4.6) {
let vmax = requestedSpeed;
const minimumDistanceFactor = 1 / acceleration + 1 / deceleration;
vmax = Math.min(vmax, Math.sqrt((2 * length) / minimumDistanceFactor));
const accelTime = vmax / acceleration;
const decelTime = vmax / deceleration;
const accelDistance = 0.5 * vmax * accelTime;
const decelDistance = 0.5 * vmax * decelTime;
const cruiseDistance = Math.max(0, length - accelDistance - decelDistance);
const cruiseTime = vmax > 0 ? cruiseDistance / vmax : 0;
const duration = accelTime + cruiseTime + decelTime;
return {
length,
vmax,
acceleration,
deceleration,
accelTime,
decelTime,
cruiseTime,
duration,
cruiseStart: accelTime,
cruiseEnd: accelTime + cruiseTime
};
}
function sampleProfile(profile, time) {
const t = THREE.MathUtils.clamp(time, 0, profile.duration);
if (t < profile.accelTime) {
return {
distance: 0.5 * profile.acceleration * t * t,
speed: profile.acceleration * t
};
}
if (t < profile.cruiseEnd) {
return {
distance: 0.5 * profile.vmax * profile.accelTime +
profile.vmax * (t - profile.accelTime),
speed: profile.vmax
};
}
const decelT = Math.min(profile.decelTime, t - profile.cruiseEnd);
const decelDistance = profile.vmax * decelT - 0.5 * profile.deceleration * decelT * decelT;
return {
distance: profile.length - 0.5 * profile.vmax * profile.decelTime + decelDistance,
speed: Math.max(0, profile.vmax - profile.deceleration * decelT)
};
}
// The route intentionally uses a clear aisle. Turn commands occur only
// after the character has stopped, so turning cannot sweep through a stall.
const commands = [
{ type: "wait", duration: 0.65 },
{ type: "move", target: [-1.60, 0.48], speed: 1.18 },
{ type: "wait", duration: 0.85 },
{ type: "turn", delta: Math.PI / 2 },
{ type: "move", target: [1.28, 0.48], speed: 1.22 },
{ type: "wait", duration: 0.75 },
{ type: "turn", delta: Math.PI / 2 },
{ type: "move", target: [1.28, -1.68], speed: 1.12 },
{ type: "wait", duration: 0.90 },
{ type: "turn", delta: Math.PI / 2 },
{ type: "move", target: [-0.88, -1.68], speed: 1.15 },
{ type: "wait", duration: 0.75 },
{ type: "turn", delta: -Math.PI / 2 },
{ type: "move", target: [-0.88, -0.96], speed: 0.95 },
{ type: "wait", duration: 0.90 },
{ type: "turn", delta: Math.PI / 2 },
{ type: "move", target: [0.56, -0.96], speed: 1.10 },
{ type: "wait", duration: 1.50 }
];
let commandIndex = 0;
let active = null;
let complete = false;
let stateLabel = "READY";
function startCommand(command) {
currentSpeed = 0;
if (command.type === "wait") {
active = {
type: "wait",
elapsed: 0,
duration: command.duration
};
stateLabel = "PAUSED";
} else if (command.type === "turn") {
active = {
type: "turn",
elapsed: 0,
duration: 0.78,
from: heading,
to: heading + command.delta
};
stateLabel = "TURNING";
} else if (command.type === "move") {
const target = new THREE.Vector3(command.target[0], 0, command.target[1]);
const direction = target.clone().sub(rootPosition);
const length = direction.length();
direction.normalize();
const profile = makeProfile(length, command.speed);
active = {
type: "move",
elapsed: 0,
start: rootPosition.clone(),
direction,
profile,
previousDistance: 0
};
gaitU = 0;
nextBoundary = 0.5;
// The right foot starts its first swing; the left foot is planted.
beginSwing(feet[1], rootPosition.clone(), direction);
stateLabel = "WALKING";
}
}
function finishMovement() {
// At a full-stride boundary both feet are grounded.
landFoot(feet[0]);
feet[1].swinging = false;
gaitU = Math.round(gaitU);
currentSpeed = 0;
}
function updateMotion(dt) {
if (complete) {
currentSpeed = 0;
stateLabel = "TOUR COMPLETE";
return;
}
if (!active) {
startCommand(commands[commandIndex]);
return;
}
active.elapsed += dt;
if (active.type === "wait") {
currentSpeed = 0;
stateLabel = "PAUSED";
if (active.elapsed >= active.duration) {
commandIndex++;
active = null;
}
return;
}
if (active.type === "turn") {
const t = THREE.MathUtils.clamp(active.elapsed / active.duration, 0, 1);
const eased = smooth01(t);
const nextHeading = THREE.MathUtils.lerp(active.from, active.to, eased);
const delta = nextHeading - heading;
// Rotate the planted feet around the body so they remain on the floor
// and preserve their front/back relationship through the turn.
feet.forEach(foot => rotateAnchorAroundRoot(foot.anchor, delta));
heading = nextHeading;
currentSpeed = 0;
stateLabel = "TURNING";
if (active.elapsed >= active.duration) {
heading = active.to;
commandIndex++;
active = null;
}
return;
}
if (active.type === "move") {
const sample = sampleProfile(active.profile, active.elapsed);
const desiredDistance = Math.min(active.profile.length, sample.distance);
const requestedDelta = desiredDistance - active.previousDistance;
const desiredPosition = active.start.clone().addScaledVector(active.direction, desiredDistance);
const requestedX = desiredPosition.x - rootPosition.x;
const requestedZ = desiredPosition.z - rootPosition.z;
const actualDelta = moveWithCollision(requestedX, requestedZ);
rootPosition.x += requestedX * (actualDelta / Math.max(0.00001, Math.hypot(requestedX, requestedZ)));
rootPosition.z += requestedZ * (actualDelta / Math.max(0.00001, Math.hypot(requestedX, requestedZ)));
updateGait(actualDelta, active.start, active.direction);
active.previousDistance = desiredDistance;
currentSpeed = sample.speed;
if (active.elapsed >= active.profile.duration) {
finishMovement();
commandIndex++;
active = null;
}
}
}
// -------------------------------------------------------------------------
// Character pose
// -------------------------------------------------------------------------
function footPose(foot) {
if (!foot.swinging) {
return {
position: foot.anchor.clone(),
contact: true
};
}
const p = THREE.MathUtils.clamp((gaitU - foot.startU) / 0.5, 0, 1);
const eased = smooth01(p);
const position = foot.swingStart.clone().lerp(foot.target, eased);
position.y = 0.065 + Math.sin(Math.PI * p) * 0.17;
return {
position,
contact: p <= 0.001 || p >= 0.999
};
}
function updateCharacter() {
actor.position.set(rootPosition.x, 0, rootPosition.z);
actor.rotation.y = heading;
const speedRatio = THREE.MathUtils.clamp(currentSpeed / 1.2, 0, 1);
const bob = speedRatio * 0.025 * (0.5 + 0.5 * Math.abs(Math.sin(Math.PI * gaitU)));
bodyPivot.position.y = bob;
bodyPivot.rotation.x = speedRatio * 0.065;
const forward = forwardVector();
const right = rightVector();
let leftContact = true;
let rightContact = true;
feet.forEach((foot, index) => {
const pose = footPose(foot);
const position = pose.position;
foot.mesh.position.copy(position);
foot.mesh.rotation.set(0, heading, 0);
if (index === 0) leftContact = pose.contact;
else rightContact = pose.contact;
const hip = rootPosition.clone()
.addScaledVector(right, foot.side);
hip.y = 0.91 + bob;
const ankle = position.clone();
ankle.y += 0.115;
// Knees bend toward the character's forward direction.
updateTwoBone(
hip,
ankle,
0.48,
0.47,
forward,
legs[index].upper,
legs[index].lower
);
});
// Arms counter-swing against the legs.
const armAmplitude = 0.25 * speedRatio;
const swing = Math.sin(Math.PI * 2 * gaitU) * armAmplitude;
arms.forEach(arm => {
const shoulder = rootPosition.clone()
.addScaledVector(right, arm.side * 0.335);
shoulder.y = 1.36 + bob;
const handOffset = arm.side < 0 ? swing : -swing;
const hand = rootPosition.clone()
.addScaledVector(right, arm.side * 0.37)
.addScaledVector(forward, handOffset);
hand.y = 0.88 + bob * 0.35;
const bend = right.clone().multiplyScalar(arm.side * 0.7)
.addScaledVector(forward, -0.25)
.normalize();
updateTwoBone(
shoulder,
hand,
0.31,
0.31,
bend,
arm.upper,
arm.lower
);
arm.hand.position.copy(hand);
arm.hand.rotation.y = heading;
});
return { leftContact, rightContact };
}
// -------------------------------------------------------------------------
// Camera controls implemented directly without external addons
// -------------------------------------------------------------------------
const cameraTarget = new THREE.Vector3(0, 0.75, 0);
let cameraYaw = 0.72;
let cameraPitch = 0.59;
let cameraDistance = 12.3;
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
function updateCamera() {
const horizontal = Math.cos(cameraPitch) * cameraDistance;
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * horizontal,
cameraTarget.y + Math.sin(cameraPitch) * cameraDistance,
cameraTarget.z + Math.cos(cameraYaw) * horizontal
);
camera.lookAt(cameraTarget);
}
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraYaw -= dx * 0.006;
cameraPitch = THREE.MathUtils.clamp(cameraPitch + dy * 0.005, 0.28, 1.25);
});
function stopDragging(event) {
dragging = false;
if (event && renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraDistance = THREE.MathUtils.clamp(
cameraDistance + event.deltaY * 0.009,
6.5,
19
);
}, { passive: false });
renderer.domElement.addEventListener("dblclick", () => {
cameraYaw = 0.72;
cameraPitch = 0.59;
cameraDistance = 12.3;
});
// -------------------------------------------------------------------------
// HUD and replay
// -------------------------------------------------------------------------
const stateElement = document.getElementById("state");
const speedElement = document.getElementById("speed");
const progressElement = document.getElementById("progress");
const leftContactElement = document.getElementById("leftContact");
const rightContactElement = document.getElementById("rightContact");
function updateHUD(contacts) {
stateElement.textContent = stateLabel;
speedElement.textContent = `${currentSpeed.toFixed(2)} m/s`;
progressElement.style.width = `${Math.min(100, commandIndex / commands.length * 100)}%`;
leftContactElement.classList.toggle("on", contacts.leftContact);
rightContactElement.classList.toggle("on", contacts.rightContact);
}
document.getElementById("replay").addEventListener("click", () => {
rootPosition.copy(START_POSITION);
heading = 0;
currentSpeed = 0;
gaitU = 0;
nextBoundary = 0.5;
commandIndex = 0;
active = null;
complete = false;
stateLabel = "READY";
initializeFeet();
});
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
updateMotion(dt);
const contacts = updateCharacter();
updateCamera();
updateHUD(contacts);
renderer.render(scene, camera);
}
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
});
updateCamera();
animate();
</script>
</body>
</html>
```