Prompt specification
Build or customize the Three.js 3D scene "Walk to Stop to Pick Up" 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: Walk to Stop to Pick Up
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/walk-to-stop-to-pick-up-x3686
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts character animation states and interrupted actions. Animate an original character slowing, planting its feet, and picking up an object. Transition states through explicit conditions and avoid sudden root-position jumps. Stylized solid forms.
Working Three.js Starter (walk-to-stop-to-pick-up-x3686):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pip — Animation State Lab</title>
<style>
:root {
color-scheme: dark;
--bg: #08141f;
--panel: rgba(10, 25, 38, 0.88);
--line: rgba(164, 213, 229, 0.18);
--text: #e9f8fb;
--muted: #91adba;
--cyan: #54e0d0;
--amber: #ffc857;
--orange: #ff805f;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
.hud {
position: fixed;
inset: 0;
pointer-events: none;
}
.panel {
pointer-events: auto;
position: absolute;
top: 22px;
left: 22px;
width: min(360px, calc(100vw - 44px));
max-height: calc(100vh - 44px);
overflow: auto;
padding: 18px;
border: 1px solid var(--line);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.28);
backdrop-filter: blur(14px);
}
.eyebrow {
margin-bottom: 5px;
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: 25px;
line-height: 1.05;
letter-spacing: -0.04em;
}
.subtitle {
margin: 8px 0 16px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.state-card {
display: flex;
align-items: center;
gap: 12px;
padding: 12px;
border: 1px solid rgba(84, 224, 208, 0.22);
border-radius: 13px;
background: rgba(84, 224, 208, 0.06);
}
.state-dot {
width: 12px;
height: 12px;
flex: 0 0 auto;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 20px currentColor;
}
.state-card[data-state="INTERRUPT"] {
border-color: rgba(255, 128, 95, 0.4);
background: rgba(255, 128, 95, 0.08);
}
.state-card[data-state="INTERRUPT"] .state-dot {
background: var(--orange);
}
.state-card[data-state="CARRY"] {
border-color: rgba(255, 200, 87, 0.35);
background: rgba(255, 200, 87, 0.07);
}
.state-card[data-state="CARRY"] .state-dot {
background: var(--amber);
}
#state-name {
font-size: 14px;
font-weight: 900;
letter-spacing: 0.08em;
}
#state-reason {
margin-top: 3px;
color: var(--muted);
font-size: 11px;
line-height: 1.35;
}
.chips {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 14px 0;
}
.chip {
padding: 6px 8px;
border: 1px solid var(--line);
border-radius: 8px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
}
.chip.active {
border-color: var(--cyan);
color: #06151b;
background: var(--cyan);
}
.chip.interrupt-chip.active {
border-color: var(--orange);
background: var(--orange);
}
.metrics {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
margin-bottom: 14px;
}
.metric {
padding: 9px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.metric span {
display: block;
color: var(--muted);
font-size: 9px;
letter-spacing: 0.05em;
text-transform: uppercase;
}
.metric strong {
display: block;
margin-top: 4px;
font-size: 12px;
font-variant-numeric: tabular-nums;
}
.section-title {
margin: 15px 0 8px;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.conditions {
margin: 0;
padding: 0;
list-style: none;
}
.conditions li {
display: grid;
grid-template-columns: 82px 1fr;
gap: 8px;
padding: 6px 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.045);
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.conditions b {
color: var(--text);
font-weight: 750;
}
.controls {
display: flex;
align-items: center;
gap: 9px;
margin-top: 15px;
}
button {
appearance: none;
border: 0;
border-radius: 10px;
padding: 10px 12px;
color: #07151b;
background: var(--cyan);
font: inherit;
font-size: 11px;
font-weight: 850;
cursor: pointer;
}
button:hover {
filter: brightness(1.08);
}
button:disabled {
opacity: 0.38;
cursor: default;
filter: none;
}
.toggle {
display: flex;
align-items: center;
gap: 7px;
color: var(--muted);
font-size: 10px;
cursor: pointer;
}
.toggle input {
accent-color: var(--orange);
}
#event-log {
display: grid;
gap: 7px;
color: var(--muted);
font-size: 10px;
line-height: 1.35;
}
.event {
display: grid;
grid-template-columns: 48px 1fr;
gap: 7px;
}
.event time {
color: var(--cyan);
font-variant-numeric: tabular-nums;
}
.camera-help {
position: absolute;
right: 22px;
bottom: 20px;
padding: 9px 12px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(8, 20, 31, 0.72);
color: var(--muted);
font-size: 10px;
backdrop-filter: blur(8px);
}
@media (max-width: 700px) {
.panel {
top: 12px;
left: 12px;
width: min(330px, calc(100vw - 24px));
max-height: calc(100vh - 24px);
padding: 14px;
}
.camera-help {
right: 12px;
bottom: 12px;
}
}
</style>
</head>
<body>
<div class="hud">
<section class="panel">
<div class="eyebrow">Motion State Lab</div>
<h1>Pip, the courier bot</h1>
<p class="subtitle">
A condition-driven animation demo: walk, decelerate, plant the feet,
reach, grab, and carry. The first reach is deliberately interrupted.
</p>
<div id="state-card" class="state-card" data-state="WALK">
<div class="state-dot"></div>
<div>
<div id="state-name">WALK</div>
<div id="state-reason">Moving toward the pickup anchor.</div>
</div>
</div>
<div class="chips">
<div class="chip active" data-chip="WALK">WALK</div>
<div class="chip" data-chip="BRAKE">BRAKE</div>
<div class="chip" data-chip="PLANT">PLANT</div>
<div class="chip" data-chip="REACH">REACH</div>
<div class="chip" data-chip="GRAB">GRAB</div>
<div class="chip" data-chip="CARRY">CARRY</div>
<div class="chip interrupt-chip" data-chip="INTERRUPT">INTERRUPT</div>
</div>
<div class="metrics">
<div class="metric">
<span>Root speed</span>
<strong id="speed-value">0.00 m/s</strong>
</div>
<div class="metric">
<span>Anchor error</span>
<strong id="error-value">0.00 m</strong>
</div>
<div class="metric">
<span>Grip gap</span>
<strong id="gap-value">0.00 m</strong>
</div>
</div>
<div class="section-title">Explicit transitions</div>
<ul class="conditions">
<li><b>WALK → BRAKE</b><span>Anchor distance ≤ 1.15 m</span></li>
<li><b>BRAKE → PLANT</b><span>|speed| ≤ 0.035 m/s AND |Δx| ≤ 0.025 m</span></li>
<li><b>PLANT → REACH</b><span>Plant blend ≥ 0.94 AND timer ≥ 0.75 s</span></li>
<li><b>REACH → GRAB</b><span>Hand-to-grip gap ≤ 0.15 m</span></li>
<li><b>GRAB → CARRY</b><span>Grip attachment confirmed</span></li>
<li><b>ANY → INTERRUPT</b><span>Interrupt flag = true</span></li>
<li><b>INTERRUPT → resume</b><span>Recovery timer ≥ 0.70 s</span></li>
</ul>
<div class="controls">
<button id="interrupt-button" type="button">Interrupt action</button>
<label class="toggle">
<input id="scripted-interrupt" type="checkbox" checked>
Scripted interruption
</label>
</div>
<div class="section-title">Transition log</div>
<div id="event-log" aria-live="polite"></div>
</section>
<div class="camera-help">
Drag to orbit · Wheel to zoom · Space to interrupt
</div>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Renderer, scene, lighting, and camera
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({ antialias: true });
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.domElement.setAttribute("aria-label", "Animated three-dimensional character scene");
document.body.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x08141f);
scene.fog = new THREE.Fog(0x08141f, 8, 19);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
60
);
const cameraTarget = new THREE.Vector3(-0.25, 0.85, 0);
let cameraYaw = 0.52;
let cameraPitch = 0.35;
let cameraRadius = 7.1;
function updateCamera() {
const horizontal = Math.cos(cameraPitch) * cameraRadius;
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * horizontal,
cameraTarget.y + Math.sin(cameraPitch) * cameraRadius,
cameraTarget.z + Math.cos(cameraYaw) * horizontal
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xb8f4ff, 0x172331, 2.2);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xfff4d6, 3.2);
keyLight.position.set(-3.5, 7, 4.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -6;
keyLight.shadow.camera.right = 6;
keyLight.shadow.camera.top = 6;
keyLight.shadow.camera.bottom = -6;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 18;
keyLight.shadow.normalBias = 0.025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4fe4db, 2.1);
rimLight.position.set(4, 3, -4);
scene.add(rimLight);
// -------------------------------------------------------------------------
// Solid-form environment
// -------------------------------------------------------------------------
const material = {
floor: new THREE.MeshStandardMaterial({
color: 0x102434,
roughness: 0.92,
metalness: 0.02
}),
floorEdge: new THREE.MeshStandardMaterial({
color: 0x193548,
roughness: 0.8
}),
teal: new THREE.MeshStandardMaterial({
color: 0x39b9aa,
roughness: 0.58,
metalness: 0.08
}),
tealDark: new THREE.MeshStandardMaterial({
color: 0x237d79,
roughness: 0.65
}),
coral: new THREE.MeshStandardMaterial({
color: 0xff805f,
roughness: 0.6
}),
amber: new THREE.MeshStandardMaterial({
color: 0xffc857,
roughness: 0.5
}),
dark: new THREE.MeshStandardMaterial({
color: 0x13212c,
roughness: 0.7
}),
rubber: new THREE.MeshStandardMaterial({
color: 0x0b151d,
roughness: 0.95
}),
cream: new THREE.MeshStandardMaterial({
color: 0xeaf8ef,
roughness: 0.75
}),
pedestal: new THREE.MeshStandardMaterial({
color: 0x28495c,
roughness: 0.8
})
};
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(18, 12),
material.floor
);
floor.rotation.x = -Math.PI / 2;
floor.receiveShadow = true;
scene.add(floor);
const platform = new THREE.Mesh(
new THREE.BoxGeometry(11.5, 0.18, 5.2),
material.floorEdge
);
platform.position.set(-0.45, -0.1, 0);
platform.receiveShadow = true;
scene.add(platform);
function addBox(parent, size, position, mat, castShadow = true) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(size.x, size.y, size.z),
mat
);
mesh.position.copy(position);
mesh.castShadow = castShadow;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addCylinder(
parent,
radiusTop,
radiusBottom,
height,
position,
mat,
segments = 12
) {
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(
radiusTop,
radiusBottom,
height,
segments
),
mat
);
mesh.position.copy(position);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addSphere(parent, radius, position, mat) {
const mesh = new THREE.Mesh(
new THREE.SphereGeometry(radius, 16, 12),
mat
);
mesh.position.copy(position);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
// Low geometric scenery.
for (const x of [-4.3, 3.8]) {
const column = addCylinder(
scene,
0.32,
0.48,
1.7,
new THREE.Vector3(x, 0.85, -2.1),
material.pedestal,
8
);
column.rotation.y = 0.3;
}
const backgroundBlock = addBox(
scene,
new THREE.Vector3(2.2, 0.9, 0.75),
new THREE.Vector3(-3.5, 0.45, 2.0),
material.pedestal
);
backgroundBlock.rotation.y = -0.2;
// Pedestal and pickup object.
const OBJECT_X = 1.14;
const OBJECT_Y = 0.775;
const OBJECT_Z = 0.22;
const GRIP_WORLD = new THREE.Vector3(
OBJECT_X - 0.25,
OBJECT_Y,
OBJECT_Z
);
addCylinder(
scene,
0.48,
0.55,
0.55,
new THREE.Vector3(OBJECT_X, 0.275, OBJECT_Z),
material.pedestal,
16
);
addCylinder(
scene,
0.5,
0.5,
0.055,
new THREE.Vector3(OBJECT_X, 0.565, OBJECT_Z),
material.coral,
16
);
const pickupObject = new THREE.Group();
pickupObject.position.set(OBJECT_X, OBJECT_Y, OBJECT_Z);
pickupObject.rotation.y = 0.18;
scene.add(pickupObject);
addBox(
pickupObject,
new THREE.Vector3(0.45, 0.45, 0.45),
new THREE.Vector3(0, 0, 0),
material.amber
);
addBox(
pickupObject,
new THREE.Vector3(0.47, 0.075, 0.47),
new THREE.Vector3(0, 0.08, 0),
material.coral
);
addBox(
pickupObject,
new THREE.Vector3(0.075, 0.47, 0.47),
new THREE.Vector3(0.06, 0, 0),
material.cream
);
// -------------------------------------------------------------------------
// Original character: Pip
// -------------------------------------------------------------------------
const root = new THREE.Group();
root.position.set(-2.35, 0, 0);
scene.add(root);
const upperBody = new THREE.Group();
root.add(upperBody);
const pelvis = addBox(
upperBody,
new THREE.Vector3(0.48, 0.25, 0.42),
new THREE.Vector3(0, 0.88, 0),
material.tealDark
);
const torsoPivot = new THREE.Group();
torsoPivot.position.set(0, 1.02, 0);
upperBody.add(torsoPivot);
addBox(
torsoPivot,
new THREE.Vector3(0.62, 0.67, 0.48),
new THREE.Vector3(0, 0.32, 0),
material.teal
);
addBox(
torsoPivot,
new THREE.Vector3(0.045, 0.29, 0.3),
new THREE.Vector3(0.325, 0.34, 0),
material.cream
);
addBox(
torsoPivot,
new THREE.Vector3(0.16, 0.15, 0.25),
new THREE.Vector3(0.355, 0.36, 0),
material.coral
);
// Small backpack makes the silhouette readable from the side.
addBox(
torsoPivot,
new THREE.Vector3(0.28, 0.43, 0.38),
new THREE.Vector3(-0.39, 0.33, 0),
material.coral
);
const head = addSphere(
torsoPivot,
0.34,
new THREE.Vector3(0, 0.89, 0),
material.cream
);
head.scale.set(1.02, 0.9, 0.95);
addBox(
torsoPivot,
new THREE.Vector3(0.075, 0.19, 0.43),
new THREE.Vector3(0.285, 0.91, 0),
material.dark
);
const eyeMaterial = new THREE.MeshStandardMaterial({
color: 0xffd86b,
emissive: 0xffb52f,
emissiveIntensity: 1.4,
roughness: 0.35
});
addSphere(
torsoPivot,
0.045,
new THREE.Vector3(0.326, 0.94, 0.115),
eyeMaterial
);
addSphere(
torsoPivot,
0.045,
new THREE.Vector3(0.326, 0.94, -0.115),
eyeMaterial
);
addCylinder(
torsoPivot,
0.035,
0.035,
0.2,
new THREE.Vector3(-0.05, 1.28, 0),
material.dark,
8
);
addSphere(
torsoPivot,
0.075,
new THREE.Vector3(-0.05, 1.4, 0),
material.coral
);
// Neck scarf.
addCylinder(
torsoPivot,
0.2,
0.2,
0.12,
new THREE.Vector3(0, 0.65, 0),
material.coral,
12
);
const boneGeometry = new THREE.CylinderGeometry(1, 1, 1, 10);
const UP = new THREE.Vector3(0, 1, 0);
function createBone(parent, radius, mat) {
const mesh = new THREE.Mesh(boneGeometry, mat);
mesh.userData.radius = radius;
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function placeBone(mesh, start, end) {
const direction = new THREE.Vector3().subVectors(end, start);
const length = Math.max(direction.length(), 0.0001);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(UP, direction.normalize());
mesh.scale.set(
mesh.userData.radius,
length,
mesh.userData.radius
);
}
// Arms are procedural two-link rigs.
const arms = {};
for (const side of [-1, 1]) {
const upper = createBone(torsoPivot, 0.085, material.teal);
const lower = createBone(torsoPivot, 0.072, material.tealDark);
const hand = addSphere(
torsoPivot,
0.105,
new THREE.Vector3(),
material.coral
);
const handAnchor = new THREE.Group();
torsoPivot.add(handAnchor);
arms[side] = { upper, lower, hand, handAnchor };
}
// Legs and planted feet.
const legs = [];
for (const side of [-1, 1]) {
const upper = createBone(root, 0.095, material.tealDark);
const lower = createBone(root, 0.082, material.dark);
const foot = addBox(
root,
new THREE.Vector3(0.43, 0.16, 0.22),
new THREE.Vector3(),
material.rubber
);
addBox(
foot,
new THREE.Vector3(0.12, 0.17, 0.235),
new THREE.Vector3(0.12, 0.005, 0),
material.coral
);
legs.push({ side, upper, lower, foot });
}
// State beacon.
const beaconMaterial = new THREE.MeshStandardMaterial({
color: 0x54e0d0,
emissive: 0x54e0d0,
emissiveIntensity: 1.3,
roughness: 0.35
});
const beacon = new THREE.Mesh(
new THREE.OctahedronGeometry(0.11),
beaconMaterial
);
beacon.position.set(0, 2.23, 0);
scene.add(beacon);
// Interruption warning.
const alertGroup = new THREE.Group();
alertGroup.visible = false;
scene.add(alertGroup);
const alertMaterial = new THREE.MeshStandardMaterial({
color: 0xff805f,
emissive: 0xff4e2e,
emissiveIntensity: 1.4
});
const alertBar = addBox(
alertGroup,
new THREE.Vector3(0.09, 0.27, 0.07),
new THREE.Vector3(0, 0.08, 0),
alertMaterial
);
addSphere(
alertGroup,
0.055,
new THREE.Vector3(0, -0.12, 0),
alertMaterial
);
const alertRingMaterial = new THREE.MeshBasicMaterial({
color: 0xff805f,
transparent: true,
opacity: 0,
depthWrite: false
});
const alertRing = new THREE.Mesh(
new THREE.TorusGeometry(0.58, 0.025, 8, 48),
alertRingMaterial
);
alertRing.rotation.x = Math.PI / 2;
scene.add(alertRing);
// -------------------------------------------------------------------------
// Explicit finite-state machine
// -------------------------------------------------------------------------
const State = Object.freeze({
WALK: "WALK",
BRAKE: "BRAKE",
PLANT: "PLANT",
REACH: "REACH",
GRAB: "GRAB",
CARRY: "CARRY",
INTERRUPT: "INTERRUPT"
});
const ANCHOR_X = 0.25;
const BRAKE_TRIGGER = 1.15;
const PLANT_DURATION = 0.75;
const INTERRUPT_DURATION = 0.70;
let state = State.WALK;
let stateTime = 0;
let rootX = -2.35;
let rootVelocity = 0;
let interruptRequested = false;
let resumeState = State.PLANT;
let scriptedInterruptUsed = false;
let carried = false;
let gaitPhase = 0;
let plantBlend = 0;
let reachBlend = 0;
let bendAmount = 0;
let interruptBlend = 0;
let gripGap = 1;
const eventLog = [];
const stateCard = document.querySelector("#state-card");
const stateName = document.querySelector("#state-name");
const stateReason = document.querySelector("#state-reason");
const speedValue = document.querySelector("#speed-value");
const errorValue = document.querySelector("#error-value");
const gapValue = document.querySelector("#gap-value");
const eventLogElement = document.querySelector("#event-log");
const interruptButton = document.querySelector("#interrupt-button");
const scriptedInterrupt = document.querySelector("#scripted-interrupt");
function transition(next, reason) {
const previous = state;
state = next;
stateTime = 0;
interruptRequested = false;
eventLog.unshift({
time: performance.now(),
text: `${previous} → ${next}: ${reason}`
});
if (eventLog.length > 5) {
eventLog.length = 5;
}
renderEventLog();
updateHud();
}
function renderEventLog() {
eventLogElement.replaceChildren();
for (const entry of eventLog) {
const row = document.createElement("div");
row.className = "event";
const time = document.createElement("time");
time.textContent = `${(entry.time / 1000).toFixed(1)}s`;
const text = document.createElement("span");
text.textContent = entry.text;
row.append(time, text);
eventLogElement.append(row);
}
}
function requestInterrupt(source = "manual request") {
if (
state === State.CARRY ||
state === State.INTERRUPT ||
state === null
) {
return;
}
if (
state === State.WALK ||
state === State.BRAKE
) {
resumeState = state;
} else {
resumeState = State.PLANT;
}
interruptRequested = true;
eventLog.unshift({
time: performance.now(),
text: `Interrupt requested: ${source}`
});
if (eventLog.length > 5) eventLog.length = 5;
renderEventLog();
}
interruptButton.addEventListener("click", () => {
requestInterrupt("manual request");
});
window.addEventListener("keydown", (event) => {
if (
event.code === "Space" &&
!["INPUT", "BUTTON"].includes(document.activeElement?.tagName)
) {
event.preventDefault();
requestInterrupt("keyboard request");
}
});
// -------------------------------------------------------------------------
// Animation utilities
// -------------------------------------------------------------------------
function damp(current, target, lambda, dt) {
return THREE.MathUtils.lerp(
current,
target,
1 - Math.exp(-lambda * dt)
);
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function solveJoint(
shoulder,
target,
lengthA,
lengthB,
bendDirection
) {
const dx = target.x - shoulder.x;
const dy = target.y - shoulder.y;
const rawDistance = Math.hypot(dx, dy);
const safeDistance = Math.max(rawDistance, 0.0001);
const ux = dx / safeDistance;
const uy = dy / safeDistance;
const distance = clamp(
rawDistance,
Math.abs(lengthA - lengthB) + 0.0001,
lengthA + lengthB - 0.0001
);
const along =
(lengthA * lengthA -
lengthB * lengthB +
distance * distance) /
(2 * distance);
const height = Math.sqrt(
Math.max(0, lengthA * lengthA - along * along)
);
const perpendicularX = -uy;
const perpendicularY = ux;
const elbow = new THREE.Vector3(
shoulder.x + ux * along + perpendicularX * height * bendDirection,
shoulder.y + uy * along + perpendicularY * height * bendDirection,
shoulder.z + (target.z - shoulder.z) * 0.5
);
const end = new THREE.Vector3(
target.x,
target.y,
target.z
);
return { elbow, end };
}
function updateLeg(leg, footTarget, bodyBob) {
const hip = new THREE.Vector3(
0,
0.87 + bodyBob,
leg.side * 0.22
);
const solution = solveJoint(
hip,
footTarget,
0.43,
0.42,
1
);
placeBone(leg.upper, hip, solution.elbow);
placeBone(leg.lower, solution.elbow, solution.end);
leg.foot.position.copy(solution.end);
}
function updateArm(side, target, reach, carrying) {
const arm = arms[side];
const shoulder = new THREE.Vector3(0, 0.54, side * 0.34);
const rest = shoulder.clone().add(
new THREE.Vector3(0.10, -1.02, side * 0.035)
);
const blendedTarget = rest.clone().lerp(target, reach);
const solution = solveJoint(
shoulder,
blendedTarget,
0.56,
0.54,
-1
);
placeBone(arm.upper, shoulder, solution.elbow);
placeBone(arm.lower, solution.elbow, solution.end);
arm.hand.position.copy(solution.end);
arm.handAnchor.position.copy(solution.end);
}
// -------------------------------------------------------------------------
// Main animation update
// -------------------------------------------------------------------------
function animateRig(dt) {
const speed = Math.abs(rootVelocity);
const gaitWeight = clamp(speed / 0.42, 0, 1);
gaitPhase += speed * dt * 6.2;
const wantsPlant =
state === State.PLANT ||
state === State.REACH ||
state === State.GRAB ||
state === State.CARRY ||
(state === State.INTERRUPT && resumeState === State.PLANT);
plantBlend = damp(plantBlend, wantsPlant ? 1 : 0, 7, dt);
const wantsReach =
state === State.REACH ||
state === State.GRAB ||
state === State.CARRY;
reachBlend = damp(reachBlend, wantsReach ? 1 : 0, 7.5, dt);
const bendTarget =
state === State.REACH || state === State.GRAB
? 0.30
: state === State.CARRY
? 0.12
: 0;
bendAmount = damp(bendAmount, bendTarget, 7, dt);
const wantsInterrupt = state === State.INTERRUPT ? 1 : 0;
interruptBlend = damp(
interruptBlend,
wantsInterrupt,
9,
dt
);
const bodyBob =
Math.abs(Math.sin(gaitPhase * 2)) * 0.035 * gaitWeight;
upperBody.position.y = bodyBob;
torsoPivot.rotation.z = -bendAmount;
torsoPivot.rotation.y = Math.sin(gaitPhase) * 0.025 * gaitWeight;
head.rotation.z = bendAmount * 0.22;
// Feet transition between cyclic gait and a fixed, wide plant stance.
for (let index = 0; index < legs.length; index++) {
const leg = legs[index];
const phase = gaitPhase + index * Math.PI;
const stride =
Math.sin(phase) * 0.32 * gaitWeight;
const lift =
Math.max(0, Math.sin(phase)) * 0.16 * gaitWeight;
const plantedX = index === 0 ? -0.18 : 0.18;
const plantedZ = leg.side * 0.32;
const footTarget = new THREE.Vector3(
THREE.MathUtils.lerp(stride, plantedX, plantBlend),
THREE.MathUtils.lerp(0.08 + lift, 0.08, plantBlend),
THREE.MathUtils.lerp(leg.side * 0.22, plantedZ, plantBlend)
);
updateLeg(leg, footTarget, bodyBob);
}
// Transform the fixed pickup point into torso-local space.
upperBody.updateMatrixWorld(true);
const pickupLocal = torsoPivot.worldToLocal(GRIP_WORLD.clone());
const supportLocal = new THREE.Vector3(
0.18,
-0.42,
-0.18
);
const carryLocal = new THREE.Vector3(
0.35,
-0.48,
0.28
);
let rightTarget;
if (carried) {
rightTarget = carryLocal;
} else {
rightTarget = pickupLocal;
}
const leftRest = new THREE.Vector3(
0.10,
-0.48,
-0.375
);
const leftTarget = leftRest.clone().lerp(
supportLocal,
reachBlend * 0.7
);
updateArm(1, rightTarget, reachBlend, carried);
updateArm(-1, leftTarget, reachBlend * 0.72, carried);
scene.updateMatrixWorld(true);
const rightHandWorld = new THREE.Vector3();
arms[1].handAnchor.getWorldPosition(rightHandWorld);
gripGap = rightHandWorld.distanceTo(GRIP_WORLD);
// Attach only after the hand is actually close to the grip.
if (
state === State.GRAB &&
!carried &&
gripGap < 0.095
) {
arms[1].handAnchor.attach(pickupObject);
carried = true;
eventLog.unshift({
time: performance.now(),
text: "GRAB → CARRY: grip attachment confirmed"
});
if (eventLog.length > 5) eventLog.length = 5;
renderEventLog();
}
// State beacon and interruption warning.
beacon.position.set(rootX, 2.23, 0);
beacon.rotation.y += dt * 1.5;
beacon.rotation.x += dt * 0.55;
const beaconColors = {
WALK: 0x54e0d0,
BRAKE: 0x7bc7ff,
PLANT: 0xffc857,
REACH: 0xffc857,
GRAB: 0xff9d59,
CARRY: 0xffc857,
INTERRUPT: 0xff805f
};
beaconMaterial.color.setHex(beaconColors[state]);
beaconMaterial.emissive.setHex(beaconColors[state]);
alertGroup.visible = interruptBlend > 0.02;
alertGroup.position.set(rootX, 2.15, 0);
alertGroup.scale.setScalar(0.75 + interruptBlend * 0.35);
alertRing.position.set(rootX, 0.025, 0);
alertRing.scale.setScalar(
0.85 + Math.sin(performance.now() * 0.009) * 0.12
);
alertRingMaterial.opacity = interruptBlend * 0.72;
if (carried) {
// A small carry motion without moving the character root.
pickupObject.rotation.z =
Math.sin(performance.now() * 0.002) * 0.035;
}
}
function updateMovement(dt) {
let desiredVelocity = 0;
if (state === State.WALK) {
desiredVelocity = 1.15;
} else if (state === State.BRAKE) {
const error = ANCHOR_X - rootX;
// A continuous velocity controller. The root is never assigned
// directly to the anchor, preventing a positional pop.
desiredVelocity = clamp(error * 3.2, -0.8, 0.8);
}
const response =
state === State.WALK
? 4.5
: state === State.BRAKE
? 6.5
: 8.5;
rootVelocity = damp(
rootVelocity,
desiredVelocity,
response,
dt
);
rootX += rootVelocity * dt;
root.position.x = rootX;
}
function evaluateTransitions() {
const anchorError = ANCHOR_X - rootX;
const absoluteError = Math.abs(anchorError);
if (interruptRequested) {
transition(
State.INTERRUPT,
"interrupt flag = true"
);
return;
}
switch (state) {
case State.WALK:
if (absoluteError <= BRAKE_TRIGGER) {
transition(
State.BRAKE,
"anchor distance ≤ 1.15 m"
);
}
break;
case State.BRAKE:
if (
stateTime > 0.65 &&
Math.abs(rootVelocity) <= 0.035 &&
absoluteError <= 0.025
) {
transition(
State.PLANT,
"|speed| ≤ 0.035 m/s AND |Δx| ≤ 0.025 m"
);
}
break;
case State.PLANT:
if (
stateTime >= PLANT_DURATION &&
plantBlend >= 0.94
) {
transition(
State.REACH,
"plant blend ≥ 0.94 AND timer ≥ 0.75 s"
);
}
break;
case State.REACH:
if (
reachBlend >= 0.92 &&
gripGap <= 0.15
) {
transition(
State.GRAB,
"hand-to-grip gap ≤ 0.15 m"
);
}
break;
case State.GRAB:
if (carried) {
transition(
State.CARRY,
"grip attachment confirmed"
);
}
break;
case State.INTERRUPT:
if (stateTime >= INTERRUPT_DURATION) {
transition(
resumeState,
"recovery timer ≥ 0.70 s"
);
}
break;
}
}
// -------------------------------------------------------------------------
// HUD
// -------------------------------------------------------------------------
function stateDescription() {
const anchorError = Math.abs(ANCHOR_X - rootX);
switch (state) {
case State.WALK:
return `Moving toward the anchor · ${anchorError.toFixed(2)} m remaining`;
case State.BRAKE:
return `Continuous deceleration · no root snap`;
case State.PLANT:
return `Locking both feet into a stable stance`;
case State.REACH:
return `Extending the right arm toward the grip`;
case State.GRAB:
return `Closing the grip after proximity is confirmed`;
case State.CARRY:
return `Object attached · walking root remains stationary`;
case State.INTERRUPT:
return `Action cancelled smoothly · recovering to ${resumeState}`;
}
}
function updateHud() {
stateCard.dataset.state = state;
stateName.textContent = state;
stateReason.textContent = stateDescription();
speedValue.textContent = `${Math.abs(rootVelocity).toFixed(2)} m/s`;
errorValue.textContent = `${Math.abs(ANCHOR_X - rootX).toFixed(2)} m`;
gapValue.textContent = `${gripGap.toFixed(2)} m`;
document.querySelectorAll("[data-chip]").forEach((chip) => {
chip.classList.toggle("active", chip.dataset.chip === state);
});
interruptButton.disabled =
state === State.CARRY ||
state === State.INTERRUPT;
}
// -------------------------------------------------------------------------
// Camera controls implemented directly in this file
// -------------------------------------------------------------------------
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
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 deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraYaw -= deltaX * 0.006;
cameraPitch = clamp(
cameraPitch + deltaY * 0.005,
0.08,
1.08
);
});
renderer.domElement.addEventListener("pointerup", (event) => {
dragging = false;
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = clamp(
cameraRadius + event.deltaY * 0.006,
4.2,
11
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
cameraYaw = 0.52;
cameraPitch = 0.35;
cameraRadius = 7.1;
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
// -------------------------------------------------------------------------
// Loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function frame() {
const dt = Math.min(clock.getDelta(), 0.05);
stateTime += dt;
if (
scriptedInterrupt.checked &&
!scriptedInterruptUsed &&
state === State.REACH &&
stateTime > 0.42
) {
scriptedInterruptUsed = true;
requestInterrupt("scripted surprise");
}
updateMovement(dt);
animateRig(dt);
evaluateTransitions();
updateHud();
updateCamera();
renderer.render(scene, camera);
}
eventLog.unshift({
time: performance.now(),
text: "WALK: demo started with continuous root velocity"
});
renderEventLog();
updateHud();
renderer.setAnimationLoop(frame);
</script>
</body>
</html>
```