Prompt specification
Build or customize the Three.js 3D scene "Shell inspection and exchange" 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: Shell inspection and exchange
Category: Biology & Nature · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/shell-inspection-and-exchange-x0694
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts hermit-crab shell use. Animate a crab approaching, inspecting, and entering a larger empty shell through a simplified sequence; keep the abandoned shell visible as a reusable object afterward. Low-poly.
Working Three.js Starter (shell-inspection-and-exchange-x0694):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hermit Crab Shell Swap</title>
<style>
:root {
--ink: #17343a;
--panel: rgba(255, 250, 238, 0.9);
--accent: #df673d;
--mint: #2d9d83;
}
* {
box-sizing: border-box;
}
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #acdce5;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
}
canvas.dragging {
cursor: grabbing;
}
.title-card {
position: absolute;
top: 20px;
left: 20px;
width: min(360px, calc(100vw - 40px));
padding: 16px 18px;
border: 1px solid rgba(23, 52, 58, 0.1);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 12px 35px rgba(34, 75, 77, 0.14);
backdrop-filter: blur(10px);
pointer-events: none;
}
.eyebrow {
margin-bottom: 4px;
color: var(--mint);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
h1 {
margin: 0;
font-size: clamp(22px, 3vw, 31px);
line-height: 1.08;
}
.subtitle {
margin: 8px 0 0;
font-size: 13px;
line-height: 1.45;
color: rgba(23, 52, 58, 0.72);
}
.stage-panel {
position: absolute;
left: 20px;
bottom: 20px;
width: min(430px, calc(100vw - 40px));
padding: 14px 16px;
border: 1px solid rgba(23, 52, 58, 0.1);
border-radius: 16px;
background: var(--panel);
box-shadow: 0 12px 35px rgba(34, 75, 77, 0.14);
backdrop-filter: blur(10px);
}
.stage-row {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
}
#stage-name {
font-weight: 800;
font-size: 16px;
}
#stage-time {
flex: 0 0 auto;
color: rgba(23, 52, 58, 0.55);
font-size: 12px;
font-variant-numeric: tabular-nums;
}
#stage-description {
min-height: 36px;
margin: 6px 0 11px;
font-size: 13px;
line-height: 1.4;
color: rgba(23, 52, 58, 0.75);
}
#timeline {
width: 100%;
height: 5px;
margin: 0;
accent-color: var(--accent);
cursor: pointer;
}
.controls {
display: flex;
gap: 8px;
margin-top: 12px;
}
button {
border: 1px solid rgba(23, 52, 58, 0.15);
border-radius: 10px;
padding: 9px 13px;
background: rgba(255, 255, 255, 0.72);
color: var(--ink);
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
transition: transform 120ms ease, background 120ms ease;
}
button:hover {
transform: translateY(-1px);
background: white;
}
button.primary {
border-color: transparent;
background: var(--accent);
color: white;
}
.help {
position: absolute;
right: 20px;
bottom: 20px;
padding: 9px 12px;
border-radius: 12px;
background: rgba(23, 52, 58, 0.72);
color: white;
font-size: 11px;
line-height: 1.35;
text-align: right;
pointer-events: none;
backdrop-filter: blur(8px);
}
.world-label {
position: absolute;
z-index: 4;
padding: 6px 9px;
border: 1px solid rgba(23, 52, 58, 0.12);
border-radius: 999px;
background: rgba(255, 252, 240, 0.92);
box-shadow: 0 5px 18px rgba(23, 52, 58, 0.13);
color: var(--ink);
font-size: 11px;
font-weight: 750;
white-space: nowrap;
pointer-events: none;
transform: translate(-50%, -100%);
}
.world-label.reusable {
border-color: rgba(45, 157, 131, 0.35);
color: #176d5c;
}
.world-label::after {
position: absolute;
top: 100%;
left: 50%;
width: 1px;
height: 15px;
background: rgba(23, 52, 58, 0.32);
content: "";
}
#toast {
position: absolute;
top: 24px;
left: 50%;
z-index: 8;
max-width: min(420px, calc(100vw - 40px));
padding: 12px 16px;
border-radius: 12px;
background: rgba(23, 52, 58, 0.9);
color: white;
box-shadow: 0 10px 30px rgba(23, 52, 58, 0.2);
font-size: 13px;
text-align: center;
opacity: 0;
pointer-events: none;
transform: translate(-50%, -12px);
transition: opacity 180ms ease, transform 180ms ease;
}
#toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
@media (max-width: 700px) {
.title-card {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 12px 14px;
}
.subtitle {
display: none;
}
.stage-panel {
left: 10px;
bottom: 10px;
width: calc(100vw - 20px);
}
.help {
display: none;
}
}
</style>
</head>
<body>
<div class="title-card">
<div class="eyebrow">Low-poly field study</div>
<h1>A Hermit Crab Finds a Better Shell</h1>
<p class="subtitle">
A simplified shell-swap sequence: approach, inspect, abandon the smaller
shell, and back into the larger empty one.
</p>
</div>
<div class="stage-panel">
<div class="stage-row">
<div id="stage-name">Approaching</div>
<div id="stage-time">0.0 / 19.0 s</div>
</div>
<p id="stage-description"></p>
<input
id="timeline"
type="range"
min="0"
max="19"
step="0.01"
value="0"
aria-label="Animation timeline"
>
<div class="controls">
<button id="play-button" class="primary" type="button">Pause</button>
<button id="replay-button" type="button">Replay</button>
<button id="camera-button" type="button">Reset view</button>
</div>
</div>
<div class="help">
Drag to orbit · Scroll to zoom<br />
Click the small shell after it is left behind
</div>
<div id="target-label" class="world-label" hidden>larger empty shell</div>
<div id="reuse-label" class="world-label reusable" hidden>
old shell · still reusable
</div>
<div id="toast" role="status" aria-live="polite"></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, 1.8));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
document.body.prepend(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xacdce5);
scene.fog = new THREE.Fog(0xacdce5, 15, 31);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraState = {
radius: 11.8,
theta: -0.46,
phi: 1.12,
target: new THREE.Vector3(0.15, 0.72, 0)
};
function resetCamera() {
cameraState.radius = window.innerWidth < 700 ? 14.6 : 11.8;
cameraState.theta = -0.46;
cameraState.phi = 1.12;
cameraState.target.set(0.15, 0.72, 0);
}
function updateCamera() {
const s = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x +
cameraState.radius * s * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z +
cameraState.radius * s * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
}
resetCamera();
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xd8f4ff, 0x9b6844, 2.1);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff1cf, 3.2);
sun.position.set(-4, 9, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -11;
sun.shadow.camera.right = 11;
sun.shadow.camera.top = 9;
sun.shadow.camera.bottom = -9;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 25;
sun.shadow.bias = -0.00035;
scene.add(sun);
const fill = new THREE.DirectionalLight(0x78c9da, 0.75);
fill.position.set(7, 4, -5);
scene.add(fill);
// -------------------------------------------------------------------------
// Materials and geometry helpers
// -------------------------------------------------------------------------
const sandMaterial = new THREE.MeshStandardMaterial({
color: 0xd9b77e,
roughness: 1,
flatShading: true,
vertexColors: true
});
const crabMaterial = new THREE.MeshStandardMaterial({
color: 0xc95335,
roughness: 0.78,
flatShading: true
});
const crabLightMaterial = new THREE.MeshStandardMaterial({
color: 0xe8784d,
roughness: 0.76,
flatShading: true
});
const darkMaterial = new THREE.MeshStandardMaterial({
color: 0x242b2b,
roughness: 0.8,
flatShading: true
});
const eyeMaterial = new THREE.MeshStandardMaterial({
color: 0xfff8dc,
roughness: 0.55,
flatShading: true
});
function makeLimb(a, b, radius, material) {
const start = new THREE.Vector3(...a);
const end = new THREE.Vector3(...b);
const direction = new THREE.Vector3().subVectors(end, start);
const length = direction.length();
const mesh = new THREE.Mesh(
new THREE.CylinderGeometry(radius * 0.78, radius, length, 6),
material
);
mesh.position.copy(start).add(end).multiplyScalar(0.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function makeShell(bodyColor, ridgeColor, scale = 1) {
const shell = new THREE.Group();
const bodyMaterial = new THREE.MeshStandardMaterial({
color: bodyColor,
roughness: 0.94,
flatShading: true
});
const ridgeMaterial = new THREE.MeshStandardMaterial({
color: ridgeColor,
roughness: 0.9,
flatShading: true
});
const apertureMaterial = new THREE.MeshStandardMaterial({
color: 0x302723,
roughness: 1,
side: THREE.DoubleSide,
flatShading: true
});
const innerMaterial = new THREE.MeshStandardMaterial({
color: 0x9e5b3d,
roughness: 1,
side: THREE.DoubleSide,
flatShading: true
});
// Faceted main whorl.
const body = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.78, 1),
bodyMaterial
);
body.scale.set(1.05, 0.8, 0.9);
body.position.x = -0.05;
body.castShadow = true;
body.receiveShadow = true;
shell.add(body);
// Raised spiral ridge on the visible side of the shell.
const spiralPoints = [];
for (let i = 0; i <= 72; i++) {
const u = i / 72;
const angle = u * Math.PI * 4.6;
const radius = 0.055 + u * 0.6;
const x = -0.16 + Math.cos(angle) * radius;
const y = Math.sin(angle) * radius * 0.77;
const surface =
0.64 *
Math.sqrt(
Math.max(
0.08,
1 - Math.pow(x / 0.82, 2) - Math.pow(y / 0.62, 2)
)
);
spiralPoints.push(new THREE.Vector3(x, y, surface + 0.018));
}
const spiralCurve = new THREE.CatmullRomCurve3(spiralPoints);
const spiral = new THREE.Mesh(
new THREE.TubeGeometry(spiralCurve, 64, 0.046, 5, false),
ridgeMaterial
);
spiral.castShadow = true;
shell.add(spiral);
// The opening faces local +X.
const opening = new THREE.Mesh(
new THREE.CircleGeometry(0.32, 12),
apertureMaterial
);
opening.rotation.y = Math.PI / 2;
opening.position.x = 0.805;
shell.add(opening);
const inner = new THREE.Mesh(
new THREE.CircleGeometry(0.245, 12),
innerMaterial
);
inner.rotation.y = Math.PI / 2;
inner.position.x = 0.818;
shell.add(inner);
const rim = new THREE.Mesh(
new THREE.TorusGeometry(0.365, 0.095, 5, 14),
ridgeMaterial
);
rim.rotation.y = Math.PI / 2;
rim.position.x = 0.855;
rim.castShadow = true;
shell.add(rim);
shell.scale.setScalar(scale);
shell.traverse((child) => {
if (child.isMesh) {
child.castShadow = true;
child.receiveShadow = true;
}
});
return shell;
}
// -------------------------------------------------------------------------
// Beach environment
// -------------------------------------------------------------------------
const groundGeometry = new THREE.PlaneGeometry(30, 12, 20, 10);
groundGeometry.rotateX(-Math.PI / 2);
groundGeometry.translate(0, 0, 1);
const groundPositions = groundGeometry.attributes.position;
const groundColors = [];
const sandA = new THREE.Color(0xd9b77e);
const sandB = new THREE.Color(0xe7ca96);
for (let i = 0; i < groundPositions.count; i++) {
const x = groundPositions.getX(i);
const z = groundPositions.getZ(i);
groundPositions.setY(
i,
Math.sin(x * 0.65) * 0.025 +
Math.cos(z * 0.85) * 0.02 +
(Math.random() - 0.5) * 0.025
);
const color = sandA.clone().lerp(
sandB,
THREE.MathUtils.clamp(0.25 + Math.random() * 0.65, 0, 1)
);
groundColors.push(color.r, color.g, color.b);
}
groundGeometry.setAttribute(
"color",
new THREE.Float32BufferAttribute(groundColors, 3)
);
groundGeometry.computeVertexNormals();
const ground = new THREE.Mesh(groundGeometry, sandMaterial);
ground.receiveShadow = true;
scene.add(ground);
const water = new THREE.Mesh(
new THREE.PlaneGeometry(40, 10),
new THREE.MeshStandardMaterial({
color: 0x55b9c7,
roughness: 0.45,
metalness: 0.05,
flatShading: true
})
);
water.rotation.x = -Math.PI / 2;
water.position.set(0, -0.08, -10);
scene.add(water);
const foamMaterial = new THREE.MeshBasicMaterial({
color: 0xd9f4ef,
transparent: true,
opacity: 0.55
});
for (let i = 0; i < 12; i++) {
const foam = new THREE.Mesh(
new THREE.BoxGeometry(1.2 + Math.random() * 2.1, 0.025, 0.08),
foamMaterial
);
foam.position.set(
-16 + i * 2.9,
0.012,
-5.05 + Math.sin(i * 1.8) * 0.18
);
foam.rotation.y = (Math.random() - 0.5) * 0.12;
scene.add(foam);
}
const rockMaterial = new THREE.MeshStandardMaterial({
color: 0x827b70,
roughness: 1,
flatShading: true
});
[
[-6.5, -3.8, 0.8, 0.48],
[-7.0, -3.6, 0.55, 0.32],
[6.0, -3.5, 1.0, 0.55],
[6.7, -3.3, 0.62, 0.36],
[4.8, 2.8, 0.58, 0.38]
].forEach(([x, z, sx, sy]) => {
const rock = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.75, 0),
rockMaterial
);
rock.position.set(x, sy * 0.5, z);
rock.scale.set(sx, sy, sx * 0.8);
rock.rotation.set(Math.random(), Math.random(), Math.random());
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
});
const grassMaterial = new THREE.MeshStandardMaterial({
color: 0x4e8d66,
roughness: 1,
flatShading: true
});
[
[-8.2, -3.2],
[-7.6, -3.6],
[7.4, -2.8],
[7.8, -3.2],
[-2.6, -4.1],
[3.1, -4.0]
].forEach(([x, z], groupIndex) => {
for (let i = 0; i < 4; i++) {
const blade = new THREE.Mesh(
new THREE.ConeGeometry(0.075, 0.75 + Math.random() * 0.5, 4),
grassMaterial
);
blade.position.set(
x + (Math.random() - 0.5) * 0.45,
0.35,
z + (Math.random() - 0.5) * 0.35
);
blade.rotation.z = (Math.random() - 0.5) * 0.35;
blade.castShadow = true;
scene.add(blade);
}
});
const pebbleMaterial = new THREE.MeshStandardMaterial({
color: 0xb39b76,
roughness: 1,
flatShading: true
});
for (let i = 0; i < 18; i++) {
const pebble = new THREE.Mesh(
new THREE.DodecahedronGeometry(0.07 + Math.random() * 0.08, 0),
pebbleMaterial
);
pebble.position.set(
-7 + Math.random() * 14,
0.045,
-2 + Math.random() * 7
);
pebble.scale.y = 0.55;
pebble.rotation.set(Math.random(), Math.random(), Math.random());
pebble.castShadow = true;
scene.add(pebble);
}
// -------------------------------------------------------------------------
// Crab model
// -------------------------------------------------------------------------
const crab = new THREE.Group();
scene.add(crab);
const crabBody = new THREE.Mesh(
new THREE.SphereGeometry(1, 9, 6),
crabMaterial
);
crabBody.position.set(-0.05, 0.02, 0);
crabBody.scale.set(0.58, 0.4, 0.68);
crabBody.castShadow = true;
crabBody.receiveShadow = true;
crab.add(crabBody);
const crabHead = new THREE.Mesh(
new THREE.SphereGeometry(1, 8, 6),
crabLightMaterial
);
crabHead.position.set(0.64, 0.08, 0);
crabHead.scale.set(0.32, 0.25, 0.35);
crabHead.castShadow = true;
crab.add(crabHead);
const eyeStalks = [];
const pupils = [];
for (const side of [-1, 1]) {
const stalk = makeLimb(
[0.58, 0.2, side * 0.2],
[0.72, 0.59, side * 0.23],
0.055,
crabMaterial
);
crab.add(stalk);
eyeStalks.push(stalk);
const eye = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.135, 1),
eyeMaterial
);
eye.position.set(0.74, 0.67, side * 0.23);
eye.castShadow = true;
crab.add(eye);
const pupil = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.058, 1),
darkMaterial
);
pupil.position.set(0.855, 0.685, side * 0.23);
crab.add(pupil);
pupils.push(pupil);
const antenna = makeLimb(
[0.7, 0.04, side * 0.12],
[1.04, 0.3, side * 0.2],
0.018,
darkMaterial
);
crab.add(antenna);
}
const clawPivots = [];
for (const side of [-1, 1]) {
const pivot = new THREE.Group();
pivot.position.set(0.43, -0.015, side * 0.49);
crab.add(pivot);
const upper = makeLimb(
[0, 0, 0],
[0.2, 0.015, -side * 0.12],
0.095,
crabMaterial
);
pivot.add(upper);
const fore = makeLimb(
[0.2, 0.015, -side * 0.12],
[0.49, 0.015, -side * 0.14],
0.08,
crabLightMaterial
);
pivot.add(fore);
const palm = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.16, 0),
crabLightMaterial
);
palm.position.set(0.51, 0.015, -side * 0.14);
palm.scale.set(1.15, 0.8, 0.9);
palm.castShadow = true;
pivot.add(palm);
const upperPincer = new THREE.Mesh(
new THREE.ConeGeometry(0.12, 0.38, 5),
crabMaterial
);
upperPincer.rotation.z = -Math.PI / 2;
upperPincer.position.set(0.7, 0.105, -side * 0.14);
upperPincer.castShadow = true;
pivot.add(upperPincer);
const lowerPincer = new THREE.Mesh(
new THREE.ConeGeometry(0.095, 0.31, 5),
crabLightMaterial
);
lowerPincer.rotation.z = -Math.PI / 2;
lowerPincer.position.set(0.66, -0.09, -side * 0.14);
lowerPincer.castShadow = true;
pivot.add(lowerPincer);
clawPivots.push(pivot);
}
const legPivots = [];
for (const side of [-1, 1]) {
for (let i = 0; i < 3; i++) {
const pivot = new THREE.Group();
pivot.position.set(-0.28 + i * 0.28, -0.02, side * 0.3);
crab.add(pivot);
const upper = makeLimb(
[0, 0, 0],
[0.18, -0.045, side * 0.37],
0.065,
crabMaterial
);
pivot.add(upper);
const lower = makeLimb(
[0.18, -0.045, side * 0.37],
[-0.015, -0.31, side * 0.72],
0.05,
crabLightMaterial
);
pivot.add(lower);
const foot = new THREE.Mesh(
new THREE.ConeGeometry(0.07, 0.22, 5),
darkMaterial
);
foot.rotation.z = Math.PI / 2;
foot.position.set(-0.1, -0.41, side * 0.9);
foot.castShadow = true;
pivot.add(foot);
legPivots.push({
pivot,
phase: i * 1.9 + (side > 0 ? Math.PI : 0)
});
}
}
// -------------------------------------------------------------------------
// The old shell and the larger empty shell
// -------------------------------------------------------------------------
const oldShell = makeShell(0x9a6848, 0xd29a68, 0.58);
scene.add(oldShell);
const targetShell = makeShell(0xc58a53, 0xf0c080, 1.12);
targetShell.position.set(2.35, 0.7, 0);
targetShell.rotation.y = Math.PI;
scene.add(targetShell);
const reuseRingMaterial = new THREE.MeshBasicMaterial({
color: 0x43b99a,
transparent: true,
opacity: 0,
side: THREE.DoubleSide,
depthWrite: false
});
const reuseRing = new THREE.Mesh(
new THREE.RingGeometry(0.57, 0.64, 28),
reuseRingMaterial
);
reuseRing.rotation.x = -Math.PI / 2;
reuseRing.position.set(-0.68, 0.035, 0.05);
scene.add(reuseRing);
// -------------------------------------------------------------------------
// Animation timeline
// -------------------------------------------------------------------------
const DURATION = 19;
const ATTACH_TIME = 12.2;
const SHED_TIME = 6.4;
let time = 0;
let playing = true;
let currentStage = -1;
const stages = [
{
start: 0,
name: "Approaching",
description:
"Still carrying its smaller shell, the crab scuttles toward a larger empty spiral shell."
},
{
start: 4.2,
name: "Inspecting",
description:
"The crab stops, raises its eyes, and taps the larger shell to compare its size and opening."
},
{
start: 6.4,
name: "Leaving the old shell",
description:
"The smaller shell is set down on the sand rather than being discarded."
},
{
start: 8.3,
name: "Entering the larger shell",
description:
"Turning around, the crab backs into the larger opening and slides its body inside."
},
{
start: 12.2,
name: "Checking the fit",
description:
"The new shell settles over the crab's abdomen while the eyes and claws remain exposed."
},
{
start: 14.7,
name: "Shell in use",
description:
"The crab moves in its upgraded shell. The smaller abandoned shell remains available for reuse."
}
];
function smooth(a, b, x) {
const u = THREE.MathUtils.clamp((x - a) / (b - a), 0, 1);
return u * u * u * (u * (u * 6 - 15) + 10);
}
function lerp(a, b, u) {
return a + (b - a) * u;
}
function poseAt(t) {
let x;
let rotation;
let moving = false;
if (t < 4.2) {
x = lerp(-3.85, 0.25, smooth(0, 4.2, t));
rotation = 0;
moving = true;
} else if (t < 6.4) {
x = lerp(0.25, 0.45, smooth(4.2, 6.4, t));
rotation = 0;
} else if (t < 8.3) {
x = lerp(0.45, 0.55, smooth(6.4, 8.3, t));
rotation = lerp(0, Math.PI, smooth(6.4, 8.3, t));
} else if (t < 12.2) {
x = lerp(0.55, 2.1, smooth(8.3, 12.2, t));
rotation = Math.PI;
moving = true;
} else if (t < 14.7) {
x = 2.1;
rotation = Math.PI;
} else {
x = lerp(2.1, 3.55, smooth(14.7, 19, t));
rotation = Math.PI;
moving = true;
}
const walkAmount = moving ? 1 : 0.16;
const bob = Math.sin(t * 11.5) * 0.035 * walkAmount;
return { x, rotation, bob, moving };
}
const oldShellFinalPosition = new THREE.Vector3(-0.68, 0.43, 0.05);
const oldShellFinalQuaternion = new THREE.Quaternion().setFromEuler(
new THREE.Euler(0, -0.35, 0)
);
function carriedShellTransform(t) {
const pose = poseAt(t);
const local = new THREE.Vector3(-0.18, 0.57, 0);
const position = local.applyAxisAngle(
new THREE.Vector3(0, 1, 0),
pose.rotation
);
position.x += pose.x;
position.y += 0.58 + pose.bob;
const quaternion = new THREE.Quaternion().setFromEuler(
new THREE.Euler(0, pose.rotation, 0)
);
return { position, quaternion };
}
function updateOldShell(t) {
if (t < SHED_TIME) {
const carried = carriedShellTransform(t);
oldShell.position.copy(carried.position);
oldShell.quaternion.copy(carried.quaternion);
} else {
const shedProgress = smooth(SHED_TIME, 7.9, t);
const start = carriedShellTransform(SHED_TIME);
const position = start.position.clone().lerp(
oldShellFinalPosition,
shedProgress
);
position.y += Math.sin(shedProgress * Math.PI) * 0.32;
oldShell.position.copy(position);
oldShell.quaternion.slerpQuaternions(
start.quaternion,
oldShellFinalQuaternion,
shedProgress
);
}
}
function updateTargetShell(t) {
if (t < ATTACH_TIME) {
if (targetShell.parent !== scene) {
scene.attach(targetShell);
}
targetShell.position.set(2.35, 0.7, 0);
targetShell.rotation.set(0, Math.PI, 0);
targetShell.scale.setScalar(1.12);
} else {
if (targetShell.parent !== crab) {
crab.attach(targetShell);
}
const fitProgress = smooth(ATTACH_TIME, 14.2, t);
const wiggle = Math.sin((t - ATTACH_TIME) * 8.5) *
Math.exp(-(t - ATTACH_TIME) * 0.65);
targetShell.position.set(
-0.25 + wiggle * 0.035,
lerp(0.12, 0.15, fitProgress),
0
);
targetShell.rotation.set(
0,
0,
wiggle * 0.025
);
targetShell.scale.setScalar(1.12);
}
}
function updateCrab(t) {
const pose = poseAt(t);
crab.position.set(pose.x, 0.58 + pose.bob, 0);
crab.rotation.y = pose.rotation;
const fold = smooth(9.4, 11.9, t);
const inspecting = t >= 4.2 && t < 6.4;
for (const { pivot, phase } of legPivots) {
const stride = Math.sin(t * 10.5 + phase);
pivot.rotation.y = stride * 0.28 * (pose.moving ? 1 : 0.18);
pivot.rotation.x = Math.cos(t * 10.5 + phase) * 0.08;
pivot.rotation.z = fold * 0.95;
}
const tap = inspecting
? Math.max(0, Math.sin((t - 4.2) * 8.4))
: 0;
clawPivots.forEach((pivot, index) => {
const sideOffset = index === 0 ? -1 : 1;
pivot.position.x = 0.43 + tap * 0.14;
pivot.rotation.z =
(index === 0 ? -0.08 : 0.08) +
tap * 0.13 +
fold * 0.28;
pivot.rotation.y =
sideOffset * 0.08 +
Math.sin(t * 9 + index) * 0.08 * (pose.moving ? 1 : 0.25);
});
crabHead.rotation.z = inspecting ? -0.09 * tap : 0;
crabHead.position.y = 0.08 + (inspecting ? tap * 0.035 : 0);
for (const stalk of eyeStalks) {
stalk.rotation.z = inspecting ? -0.07 * tap : 0;
}
for (const pupil of pupils) {
pupil.position.y = 0.685 + (inspecting ? tap * 0.02 : 0);
}
}
function updateStage(t) {
let stageIndex = 0;
for (let i = 0; i < stages.length; i++) {
if (t >= stages[i].start) {
stageIndex = i;
}
}
if (stageIndex !== currentStage) {
currentStage = stageIndex;
stageName.textContent = stages[stageIndex].name;
stageDescription.textContent = stages[stageIndex].description;
}
stageTime.textContent = `${t.toFixed(1)} / ${DURATION.toFixed(1)} s`;
timeline.value = t;
progressFill.style.width = `${(t / DURATION) * 100}%`;
}
// -------------------------------------------------------------------------
// Labels and optional interaction with the reusable shell
// -------------------------------------------------------------------------
const targetLabel = document.getElementById("target-label");
const reuseLabel = document.getElementById("reuse-label");
const toast = document.getElementById("toast");
const projectedPoint = new THREE.Vector3();
function placeWorldLabel(element, worldPosition, visible) {
if (!visible) {
element.hidden = true;
return;
}
projectedPoint.copy(worldPosition).project(camera);
const onScreen =
projectedPoint.z > -1 &&
projectedPoint.z < 1 &&
Math.abs(projectedPoint.x) < 1.15 &&
Math.abs(projectedPoint.y) < 1.15;
element.hidden = !onScreen;
if (!onScreen) return;
element.style.left = `${(projectedPoint.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-projectedPoint.y * 0.5 + 0.5) * window.innerHeight}px`;
}
let toastTimeout;
function showToast(message) {
toast.textContent = message;
toast.classList.add("visible");
clearTimeout(toastTimeout);
toastTimeout = setTimeout(() => {
toast.classList.remove("visible");
}, 2800);
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
let pointerDown = null;
renderer.domElement.addEventListener("pointerdown", (event) => {
pointerDown = {
x: event.clientX,
y: event.clientY
};
renderer.domElement.classList.add("dragging");
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointerDown) return;
const dx = event.clientX - pointerDown.x;
const dy = event.clientY - pointerDown.y;
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.005,
0.55,
1.43
);
pointerDown.x = event.clientX;
pointerDown.y = event.clientY;
updateCamera();
});
renderer.domElement.addEventListener("pointerup", (event) => {
renderer.domElement.classList.remove("dragging");
if (!pointerDown) return;
const movement = Math.hypot(
event.clientX - pointerDown.x,
event.clientY - pointerDown.y
);
pointerDown = null;
if (movement > 5 || time < 7.2) return;
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObject(oldShell, true);
if (hits.length) {
showToast(
"This smaller shell was left behind, but it can still be reused by another hermit crab."
);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
pointerDown = null;
renderer.domElement.classList.remove("dragging");
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
6.5,
18
);
updateCamera();
},
{ passive: false }
);
// -------------------------------------------------------------------------
// UI and playback
// -------------------------------------------------------------------------
const stageName = document.getElementById("stage-name");
const stageDescription = document.getElementById("stage-description");
const stageTime = document.getElementById("stage-time");
const timeline = document.getElementById("timeline");
const playButton = document.getElementById("play-button");
const replayButton = document.getElementById("replay-button");
const cameraButton = document.getElementById("camera-button");
const progressFill = document.createElement("div");
timeline.style.background =
"linear-gradient(to right, #df673d 0%, #df673d 0%, rgba(23,52,58,.15) 0%)";
function updateProgressStyle() {
const percentage = (time / DURATION) * 100;
timeline.style.background =
`linear-gradient(to right, #df673d 0%, #df673d ${percentage}%, ` +
`rgba(23,52,58,.15) ${percentage}%, rgba(23,52,58,.15) 100%)`;
}
function resetAnimation() {
time = 0;
playing = true;
currentStage = -1;
if (targetShell.parent !== scene) {
scene.attach(targetShell);
}
targetShell.position.set(2.35, 0.7, 0);
targetShell.rotation.set(0, Math.PI, 0);
targetShell.scale.setScalar(1.12);
playButton.textContent = "Pause";
updateProgressStyle();
}
playButton.addEventListener("click", () => {
if (time >= DURATION) {
resetAnimation();
return;
}
playing = !playing;
playButton.textContent = playing ? "Pause" : "Play";
});
replayButton.addEventListener("click", resetAnimation);
cameraButton.addEventListener("click", () => {
resetCamera();
updateCamera();
});
timeline.addEventListener("input", () => {
time = Number(timeline.value);
playing = false;
playButton.textContent = "Play";
updateProgressStyle();
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 1.8));
});
// -------------------------------------------------------------------------
// Main loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
const labelPosition = new THREE.Vector3();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (playing) {
time = Math.min(DURATION, time + dt);
if (time >= DURATION) {
playing = false;
playButton.textContent = "Play";
}
}
updateCrab(time);
updateOldShell(time);
updateTargetShell(time);
updateStage(time);
updateProgressStyle();
const pulse = 0.5 + 0.5 * Math.sin(time * 3.1);
reuseRingMaterial.opacity =
time > 7.5 ? 0.12 + pulse * 0.22 : 0;
scene.updateMatrixWorld(true);
targetShell.getWorldPosition(labelPosition);
labelPosition.y += 1.0;
placeWorldLabel(
targetLabel,
labelPosition,
time > 2.8 && time < ATTACH_TIME
);
oldShell.getWorldPosition(labelPosition);
labelPosition.y += 0.78;
placeWorldLabel(
reuseLabel,
labelPosition,
time > 7.3
);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```