Project Goal: Create an interactive 3D web application using Three.js to demonstrate advanced procedural spider animation using THREE.IK.
Core Requirements:
Procedurally Animated Spider:
Create a spider model composed of a body and eight multi-jointed legs.
Implement a procedural animation system where the spider's legs automatically adapt to the ground beneath them.
Allow the user to control the spider's movement direction with keyboard inputs (W, A, S, D).
Implement a mouse-controlled orbital camera to view the spider from any angle.
Test Environment:
-Generate a simple, non-flat ground plane with varied heights (hills and valleys) so the animation can be properly tested.
-Scatter a few basic obstacles (like spheres or boxes) on the terrain.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Procedural Spider Animation with Three.js & THREE.IK</title>
<style>
body { margin: 0; overflow: hidden; font-family: Arial, sans-serif; }
canvas { display: block; }
#info {
position: absolute;
top: 10px;
left: 10px;
color: white;
background: rgba(0, 0, 0, 0.5);
padding: 8px 12px;
border-radius: 5px;
font-size: 14px;
user-select: none; /* Prevent text selection */
}
</style>
</head>
<body>
<div id="info">
<strong>Procedural Spider Animation</strong><br>
Controls: WASD to move. Mouse to orbit camera.
</div>
<canvas id="webgl-canvas"></canvas>
<!-- Libraries -->
<!-- THREE.js Core -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!-- THREE.js OrbitControls -->
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<!-- THREE.IK Library -->
<script src="https://cdn.jsdelivr.net/npm/three-ik@0.1.0/build/three-ik.min.js"></script>
<!-- Custom Application Script -->
<script>
// --- Global Variables ---
let scene, camera, renderer, controls, clock;
let groundMesh;
let spiderBody;
let spiderLegs = []; // Array to hold leg IK data structures
// Spider State Object: Manages position, rotation, speed, and velocity
const spider = {
position: new THREE.Vector3(), // Current world position
rotationY: 0, // Current rotation around Y axis (radians)
speed: 2.0, // Base movement speed (units per second)
turnSpeed: Math.PI * 1.2, // Base turning speed (radians per second)
currentForwardVelocity: 0, // Current forward/backward velocity, smoothed
currentTurnVelocity: 0 // Current turning velocity, smoothed
};
// Input State: Tracks currently pressed movement keys
const spiderMoveState = { forward: 0, turn: 0 }; // -1: backward, 0: stop, 1: forward | -1: left, 0: stop, 1: right
// Raycaster for ground detection
let raycaster = new THREE.Raycaster();
// Gait Parameters: Define the spider's walking pattern
const NUM_LEGS = 8;
const LEG_BASE_OFFSETS = []; // Pre-calculated positions of each leg's hip joint relative to the spider's body center
const LEG_SEGMENT_LENGTHS = []; // Lengths of leg segments (hip-to-knee, knee-to-ankle, ankle-to-foot)
const LEG_JOINT_LIMITS = []; // Constraints for joint rotations (min/max angles)
const GAIT_STEP_LENGTH = 0.5; // Maximum forward/backward reach of a foot during its swing phase
const GAIT_STEP_HEIGHT = 0.2; // Maximum height a foot lifts off the ground during its swing phase
const GAIT_CYCLE_DURATION = 1.2; // Time (seconds) for a complete gait cycle (e.g., all legs move once)
let currentGaitPhase = 0; // Tracks the progress of the gait cycle (0.0 to 1.0)
/**
* Initializes leg geometry data like base offsets, segment lengths, and joint limits.
* This defines the spider's proportions and skeletal structure.
*/
function setupLegGeometry() {
const bodyRadius = 0.5;
const legRadius = 0.08;
const segment1Length = 0.6; // Hip to Knee
const segment2Length = 0.5; // Knee to Ankle
const segment3Length = 0.3; // Ankle to Foot Tip
// Define the starting positions (offsets) of the 8 leg hip joints relative to the spider's body center.
// These are arranged somewhat symmetrically around the body.
const legOffsets8 = [
// Front cluster
new THREE.Vector3( bodyRadius * 0.6, -bodyRadius * 0.1, bodyRadius * 1.1), // Leg 0: Front-Left relative
new THREE.Vector3(-bodyRadius * 0.6, -bodyRadius * 0.1, bodyRadius * 1.1), // Leg 1: Front-Right relative
// Mid-front cluster
new THREE.Vector3( bodyRadius * 1.0, -bodyRadius * 0.1, bodyRadius * 0.5), // Leg 2: Mid-Front-Left relative
new THREE.Vector3(-bodyRadius * 1.0, -bodyRadius * 0.1, bodyRadius * 0.5), // Leg 3: Mid-Front-Right relative
// Mid-back cluster
new THREE.Vector3( bodyRadius * 1.0, -bodyRadius * 0.1, -bodyRadius * 0.5), // Leg 4: Mid-Back-Left relative
new THREE.Vector3(-bodyRadius * 1.0, -bodyRadius * 0.1, -bodyRadius * 0.5), // Leg 5: Mid-Back-Right relative
// Back cluster
new THREE.Vector3( bodyRadius * 0.6, -bodyRadius * 0.1, -bodyRadius * 1.1), // Leg 6: Back-Left relative
new THREE.Vector3(-bodyRadius * 0.6, -bodyRadius * 0.1, -bodyRadius * 1.1), // Leg 7: Back-Right relative
];
// Populate the global arrays with data for each leg
for (let i = 0; i < NUM_LEGS; i++) {
LEG_BASE_OFFSETS.push(legOffsets8[i]);
LEG_SEGMENT_LENGTHS.push({
hipToKnee: segment1Length,
kneeToAnkle: segment2Length,
ankleToFoot: segment3Length
});
// Define joint limits in radians. These constrain the IK solver.
LEG_JOINT_LIMITS.push({
hipPitch: { min: -Math.PI / 3, max: Math.PI / 3 }, // Forward/Backward bend at the hip
hipYaw: { min: -Math.PI / 4, max: Math.PI / 4 }, // Side-to-side bend at the hip
kneePitch: { min: 0, max: 2 * Math.PI / 3 } // Forward bend range at the knee
});
}
}
/**
* Creates the spider model, including the body and the skeletal structure for each leg.
* Sets up the IK chains using the THREE.IK library.
* @returns {THREE.Group} The main group containing the entire spider model.
*/
function createSpider() {
const spiderGroup = new THREE.Group(); // Main container for the spider
// --- Spider Body ---
const bodyGeometry = new THREE.SphereGeometry(0.5, 32, 16);
const bodyMaterial = new THREE.MeshPhongMaterial({ color: 0x333333 }); // Dark grey body
const bodyMesh = new THREE.Mesh(bodyGeometry, bodyMaterial);
bodyMesh.castShadow = true; // Body casts shadows
spiderGroup.add(bodyMesh);
// --- Spider Legs ---
const legRadius = 0.08; // Radius for leg segments
const segmentMaterial = new THREE.MeshPhongMaterial({ color: 0x444444 }); // Darker grey for segments
const legEndMaterial = new THREE.MeshPhongMaterial({ color: 0x555555 }); // Slightly lighter grey for foot
for (let i = 0; i < NUM_LEGS; i++) {
// legData will store references to the joints, IK instances, and the foot target for this leg.
const legData = {
joints: [], // Array storing { jointObject, ikInstance } for each joint in the chain
ikChainBones: [], // Stores the actual IK objects used by the solver
parentGroup: null // The group holding this leg's structure (attached to spiderGroup)
};
// Create a group for the entire leg, positioned by its base offset
const legGroup = new THREE.Group();
legGroup.position.copy(LEG_BASE_OFFSETS[i]);
spiderGroup.add(legGroup);
legData.parentGroup = legGroup;
// --- Hip Joint ---
const hipJoint = new THREE.Group();
legGroup.add(hipJoint); // Hip is the root of the leg's hierarchy
// Hip Segment Mesh (connects hip to knee) - Grows along the Z axis
const hipSegMesh = new THREE.Mesh(
new THREE.CylinderGeometry(legRadius, legRadius, LEG_SEGMENT_LENGTHS[i].hipToKnee, 16),
segmentMaterial
);
hipSegMesh.position.set(0, 0, LEG_SEGMENT_LENGTHS[i].hipToKnee / 2);
hipJoint.add(hipSegMesh);
// --- Knee Joint ---
const kneeJoint = new THREE.Group();
// Position knee joint at the end of the hip segment
kneeJoint.position.set(0, 0, LEG_SEGMENT_LENGTHS[i].hipToKnee);
hipJoint.add(kneeJoint);
// Knee Segment Mesh (connects knee to ankle) - Grows along Z
const kneeSegMesh = new THREE.Mesh(
new THREE.CylinderGeometry(legRadius, legRadius, LEG_SEGMENT_LENGTHS[i].kneeToAnkle, 16),
segmentMaterial
);
kneeSegMesh.position.set(0, 0, LEG_SEGMENT_LENGTHS[i].kneeToAnkle / 2);
kneeJoint.add(kneeSegMesh);
// --- Ankle Joint ---
const ankleJoint = new THREE.Group();
// Position ankle joint at the end of the knee segment
ankleJoint.position.set(0, 0, LEG_SEGMENT_LENGTHS[i].kneeToAnkle);
kneeJoint.add(ankleJoint);
// Ankle Segment Mesh (connects ankle to foot) - Grows along Z
const ankleSegMesh = new THREE.Mesh(
new THREE.CylinderGeometry(legRadius, legRadius, LEG_SEGMENT_LENGTHS[i].ankleToFoot, 16),
segmentMaterial
);
ankleSegMesh.position.set(0, 0, LEG_SEGMENT_LENGTHS[i].ankleToFoot / 2);
ankleJoint.add(ankleSegMesh);
// --- Foot Target ---
// This Object3D represents the desired end position of the foot.
// The IK solver will try to move this object by rotating the joints.
const footTarget = new THREE.Object3D();
// Position the target at the end of the ankle segment
footTarget.position.set(0, 0, LEG_SEGMENT_LENGTHS[i].ankleToFoot);
ankleJoint.add(footTarget);
// --- Foot Marker (Visual Aid) ---
const footMarker = new THREE.Mesh(new THREE.SphereGeometry(legRadius * 1.2, 8, 8), legEndMaterial);
footMarker.position.copy(footTarget.position); // Place marker visually at the target
ankleJoint.add(footMarker);
// --- Setup IK Chain ---
// The `three-ik` library works with a chain of IK objects, where each object represents a joint.
// The last IK object in the chain needs the 'target' property set to the effector object (footTarget).
const ikChainBones = [];
// Hip Joint IK Setup
ikChainBones.push(new IK(hipJoint, {
rotationAxis: 'x', // Rotation around X controls pitch (forward/backward bend)
limitConst: LEG_JOINT_LIMITS[i].hipPitch
}));
// Knee Joint IK Setup
ikChainBones.push(new IK(kneeJoint, {
rotationAxis: 'x', // Rotation around X controls pitch (bending the leg)
limitConst: LEG_JOINT_LIMITS[i].kneePitch
}));
// Ankle Joint IK Setup (Effecting Bone)
ikChainBones.push(new IK(ankleJoint, {
rotationAxis: 'x', // Rotation around X controls foot pitch
target: footTarget // THIS IS CRUCIAL: Links the IK chain to the target position
}));
// Store the chain and associated data for this leg
legData.ikChainBones = ikChainBones;
spiderLegs.push(legData);
}
return spiderGroup;
}
/**
* Creates a procedural ground plane with varying heights (hills and valleys).
* @returns {THREE.Mesh} The ground mesh.
*/
function createGround() {
const width = 20;
const height = 20;
const segments = 64; // Increase segments for smoother terrain
// Start with a standard PlaneGeometry
const geometry = new THREE.PlaneGeometry(width, height, segments, segments);
// Modify vertex positions to create terrain height variations
const pos = geometry.attributes.position;
const noiseScale = 0.08; // Controls the frequency/waviness of the terrain
const heightMultiplier = 1.8; // Controls the amplitude/height of the terrain features
for (let i = 0; i < pos.count; i++) {
const x = pos.getX(i);
const z = pos.getZ(i);
// Use multiple sine waves for a Perlin noise-like effect (simpler approximation)
let y = 0;
y += Math.sin(x * noiseScale * 1.2 + 10.2) * heightMultiplier * 0.8;
y += Math.cos(z * noiseScale * 0.8 - 5.5) * heightMultiplier * 0.6;
y += Math.sin((x + z) * noiseScale * 0.5) * heightMultiplier * 0.4;
y = y / (0.8 + 0.6 + 0.4); // Normalize the combined height
pos.setY(i, y); // Set the calculated height for the vertex
}
geometry.computeVertexNormals(); // Update normals for correct lighting
geometry.normalsNeedUpdate = true;
// Create the ground mesh with a Phong material
const material = new THREE.MeshPhongMaterial({ color: 0x777777, side: THREE.DoubleSide }); // Grey material
groundMesh = new THREE.Mesh(geometry, material);
groundMesh.rotation.x = -Math.PI / 2; // Rotate the plane to lie flat horizontally
groundMesh.receiveShadow = true; // Allow the ground to receive shadows
return groundMesh;
}
/**
* Creates and places simple obstacles (spheres/boxes) on the terrain.
* @returns {Array<THREE.Mesh>} An array of obstacle meshes.
*/
function createObstacles() {
const obstacles = [];
const sphereGeometry = new THREE.SphereGeometry(0.4, 16, 16);
const boxGeometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
const obstacleMaterial = new THREE.MeshPhongMaterial({ color: 0x995533 }); // Brown color for obstacles
const numObstacles = 7;
const placementRadius = 15; // Limit obstacle placement to this radius from the center
for (let i = 0; i < numObstacles; i++) {
let obstacleMesh;
// Randomly choose mesh type and size
if (Math.random() > 0.5) {
obstacleMesh = new THREE.Mesh(sphereGeometry, obstacleMaterial);
obstacleMesh.scale.setScalar(0.5 + Math.random() * 0.6); // Random sphere size
} else {
obstacleMesh = new THREE.Mesh(boxGeometry, obstacleMaterial);
// Random dimensions for the box
obstacleMesh.scale.set(0.4 + Math.random() * 0.4, 0.6 + Math.random() * 0.8, 0.4 + Math.random() * 0.4);
}
let attempts = 0; // Prevent infinite loops if placement fails
let placed = false;
while (!placed && attempts < 50) {
attempts++;
// Generate random X, Z coordinates
const x = (Math.random() - 0.5) * placementRadius;
const z = (Math.random() - 0.5) * placementRadius;
// Avoid placing obstacles too close to the spider's initial position (0,0,0)
if (Math.abs(x) < 4 && Math.abs(z) < 4) continue;
// Raycast down from a point above (x, z) to find the ground height
const rayOrigin = new THREE.Vector3(x, 10, z); // Start ray high up
raycaster.set(rayOrigin, new THREE.Vector3(0, -1, 0)); // Ray direction is downwards
// Intersect only with the ground mesh
const intersects = raycaster.intersectObject(groundMesh);
if (intersects.length > 0) {
const groundHeight = intersects[0].point.y;
// Calculate the obstacle's height for positioning
let obstacleHeight = 0;
if (obstacleMesh.geometry.boundingBox) {
obstacleMesh.geometry.computeBoundingBox(); // Ensure bounding box is calculated
// Use scale to get actual height from bounding box dimensions
obstacleHeight = obstacleMesh.geometry.boundingBox.max.y * obstacleMesh.scale.y;
} else { // For SphereGeometry, radius is half the height
obstacleHeight = obstacleMesh.scale.y; // Sphere radius is half the height
}
// Position the obstacle's center so its base rests on the ground
obstacleMesh.position.set(x, groundHeight + obstacleHeight / 2, z);
obstacles.push(obstacleMesh);
obstacleMesh.castShadow = true; // Obstacles should cast shadows
placed = true; // Mark as placed and exit loop
}
}
}
return obstacles;
}
/**
* Initializes the Three.js scene, camera, renderer, controls, and loads objects.
*/
function init() {
// --- Scene Setup ---
scene = new THREE.Scene();
scene.background = new THREE.Color(0x8899aa); // Light sky-blue background
scene.fog = new THREE.Fog(0x8899aa, 15, 40); // Add fog for depth
// --- Camera Setup ---
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(0, 4, 6); // Initial camera position
// --- Renderer Setup ---
const canvas = document.getElementById('webgl-canvas');
renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio); // Use device pixel ratio for sharper rendering
renderer.shadowMap.enabled = true; // Enable shadows globally
renderer.shadowMap.type = THREE.PCFSoftShadowMap; // Use softer shadows
// --- Orbit Controls ---
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // Enable smooth camera damping
controls.dampingFactor = 0.1;
controls.screenSpacePanning = false; // Prevent panning affecting target
controls.minDistance = 2; // Minimum zoom distance
controls.maxDistance = 25; // Maximum zoom distance
// Target will be updated dynamically based on spider position
// --- Lighting ---
// Ambient light provides base illumination
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
// Directional light simulates sunlight
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.9);
directionalLight.position.set(5, 10, 7); // Light direction
directionalLight.castShadow = true; // Enable shadow casting
// Configure shadow properties for better quality
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
directionalLight.shadow.camera.near = 0.5;
directionalLight.shadow.camera.far = 50;
directionalLight.shadow.camera.left = -20;
directionalLight.shadow.camera.right = 20;
directionalLight.shadow.camera.top = 20;
directionalLight.shadow.camera.bottom = -20;
scene.add(directionalLight);
// --- Create Scene Objects ---
groundMesh = createGround();
scene.add(groundMesh);
const obstacles = createObstacles();
obstacles.forEach(obs => scene.add(obs));
// Initialize spider geometry and create the spider model
setupLegGeometry();
spiderBody = createSpider();
scene.add(spiderBody);
// --- Initial Spider Positioning ---
// Place the spider correctly on the ground at the start
const initialRayOrigin = spiderBody.position.clone();
initialRayOrigin.y += 1.0; // Start raycast slightly above the body center
raycaster.set(initialRayOrigin, new THREE.Vector3(0, -1, 0)); // Ray points down
const groundIntersects = raycaster.intersectObject(groundMesh);
if (groundIntersects.length > 0) {
// Set spider's position based on ground height + half its body height
spiderBody.position.y = groundIntersects[0].point.y + 0.5;
spider.position.copy(spiderBody.position); // Sync spider state position
// Update orbit controls target to focus on the spider
controls.target.set(spiderBody.position.x, spiderBody.position.y, spiderBody.position.z);
}
// --- Event Listeners ---
window.addEventListener('resize', onWindowResize); // Handle window resizing
window.addEventListener('keydown', onKeyDown); // Handle key presses
window.addEventListener('keyup', onKeyUp); // Handle key releases
clock = new THREE.Clock(); // Initialize clock for frame timing
}
/**
* Handles window resizing to update camera and renderer dimensions.
*/
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix(); // Update camera perspective
renderer.setSize(window.innerWidth, window.innerHeight); // Update renderer size
}
/**
* Processes keydown events to update the spider's movement state.
* @param {KeyboardEvent} event The keyboard event object.
*/
function onKeyDown(event) {
switch (event.key.toLowerCase()) {
case 'w': spiderMoveState.forward = 1; break; // Move forward
case 's': spiderMoveState.forward = -1; break; // Move backward
case 'a': spiderMoveState.turn = 1; break; // Turn left
case 'd': spiderMoveState.turn = -1; break; // Turn right
}
}
/**
* Processes keyup events to stop the spider's movement when keys are released.
* @param {KeyboardEvent} event The keyboard event object.
*/
function onKeyUp(event) {
switch (event.key.toLowerCase()) {
case 'w': if (spiderMoveState.forward === 1) spiderMoveState.forward = 0; break;
case 's': if (spiderMoveState.forward === -1) spiderMoveState.forward = 0; break;
case 'a': if (spiderMoveState.turn === 1) spiderMoveState.turn = 0; break;
case 'd': if (spiderMoveState.turn === -1) spiderMoveState.turn = 0; break;
}
}
/**
* Updates the spider's position, rotation, and procedural leg animations each frame.
* @param {number} deltaTime Time elapsed since the last frame.
*/
function updateSpider(deltaTime) {
// Calculate vectors representing the spider's orientation in world space
const spiderForwardVector = new THREE.Vector3(0, 0, -1).applyQuaternion(spiderBody.quaternion); // Spider's local forward direction
const spiderUpVector = new THREE.Vector3(0, 1, 0); // Spider's local up direction
// --- Smooth Velocity Updates ---
// Apply smoothing to movement and turning for less jerky motion
const targetForwardVelocity = spiderMoveState.forward * spider.speed;
const targetTurnVelocity = spiderMoveState.turn * spider.turnSpeed;
const smoothingFactor = 0.1; // Adjust for responsiveness vs smoothness
spider.currentForwardVelocity = THREE.MathUtils.lerp(
spider.currentForwardVelocity, targetForwardVelocity, smoothingFactor
);
spider.currentTurnVelocity = THREE.MathUtils.lerp(
spider.currentTurnVelocity, targetTurnVelocity, smoothingFactor
);
// --- Update Spider Rotation ---
if (Math.abs(spider.currentTurnVelocity) > 0.01) {
spider.rotationY += spider.currentTurnVelocity * deltaTime; // Update rotation state
spiderBody.rotation.y = spider.rotationY; // Apply rotation to the model
// Update orbit controls target to follow spider's rotation
controls.target.set(spiderBody.position.x, spiderBody.position.y, spiderBody.position.z);
}
// --- Update Spider Position ---
if (Math.abs(spider.currentForwardVelocity) > 0.01) {
// Move the spider forward/backward based on its current velocity and orientation
spider.position.add(spiderForwardVector.multiplyScalar(spider.currentForwardVelocity * deltaTime));
spiderBody.position.copy(spider.position); // Update the actual mesh position
// Update orbit controls target to follow spider's movement
controls.target.set(spiderBody.position.x, spiderBody.position.y, spiderBody.position.z);
}
// --- Gait Animation Logic ---
// Adjust gait speed based on how fast the spider is moving
let gaitSpeedMultiplier = 0.5; // Default slower gait
if (Math.abs(spider.currentForwardVelocity) > 0.1) {
// Faster movement = faster gait cycle
gaitSpeedMultiplier = 1.0 + Math.abs(spider.currentForwardVelocity) / spider.speed * 0.7;
}
// Update the global gait phase, cycling based on delta time and speed multiplier
currentGaitPhase = (currentGaitPhase + deltaTime / GAIT_CYCLE_DURATION * gaitSpeedMultiplier) % 1.0;
// Determine which legs should be swinging based on the gait phase (e.g., Tripod Gait)
const swingPhaseDuration = 0.5; // Each leg group swings for half the cycle duration
const isPhaseA = currentGaitPhase < swingPhaseDuration; // Check if we are in the first half of the cycle
// Define leg groups for tripod gait (alternating legs)
const swingLegIndices = isPhaseA ? [0, 2, 4, 6] : [1, 3, 5, 7];
// const plantLegIndices = isPhaseA ? [1, 3, 5, 7] : [0, 2, 4, 6]; // Not strictly needed for logic here
// Iterate through each leg to update its IK target position
for (let i = 0; i < NUM_LEGS; i++) {
const legData = spiderLegs[i];
const legOffset = LEG_BASE_OFFSETS[i]; // Base position relative to spider center
const legTargetObject = legData.ikChainBones[legData.ikChainBones.length - 1].ik.target; // Get the actual foot target Object3D
let targetPositionWorld = new THREE.Vector3(); // Calculate desired foot position in world space
const isLegSwinging = swingLegIndices.includes(i); // Check if this leg is in its swing phase
if (isLegSwinging) {
// --- Leg is Swinging ---
// Calculate progress within this leg's swing phase (0 to 1)
let swingProgress = currentGaitPhase / swingPhaseDuration;
if (!isPhaseA) { // Adjust calculation for the second half of the cycle
swingProgress = (currentGaitPhase - swingPhaseDuration) / swingPhaseDuration;
}
swingProgress = Math.max(0, Math.min(1, swingProgress)); // Clamp progress to [0, 1]
// Calculate horizontal displacement (forward) using a sine wave for an arc motion
const forwardDisplacement = GAIT_STEP_LENGTH * Math.sin(swingProgress * Math.PI);
// Calculate vertical lift using a sine wave
const verticalLift = GAIT_STEP_HEIGHT * Math.sin(swingProgress * Math.PI);
// Calculate the target position relative to the spider's body center
const legTargetRelative = legOffset.clone();
// Add the calculated forward displacement relative to the spider's forward direction
legTargetRelative.add(spiderForwardVector.clone().multiplyScalar(forwardDisplacement));
// Adjust Y position for the lift (subtracting because positive Y is up, lifting the foot)
legTargetRelative.y -= verticalLift;
// Convert the relative leg target position to world space
targetPositionWorld.copy(spider.position); // Start with spider's body world position
legTargetRelative.applyQuaternion(spiderBody.quaternion); // Apply spider's rotation to the relative offset
targetPositionWorld.add(legTargetRelative); // Add the rotated offset to get the final world position
} else {
// --- Leg is Planted or Transitioning ---
// Position the foot relative to the spider's current body position and orientation
const legTargetRelative = legOffset.clone();
legTargetRelative.applyQuaternion(spiderBody.quaternion);
targetPositionWorld.copy(spider.position).add(legTargetRelative);
// Add a slight adjustment for planted legs to simulate foot contact mechanics
// If moving forward, planted legs effectively push backward relative to the spider
if (Math.abs(spider.currentForwardVelocity) > 0.1) {
// Push backward slightly relative to spider's forward direction
const plantedRetraction = 0.15 * Math.sign(spider.currentForwardVelocity);
targetPositionWorld.sub(spiderForwardVector.multiplyScalar(plantedRetraction));
}
}
// --- Raycast for Ground Height ---
// Cast a ray downwards from slightly above the calculated target position to find the ground surface.
const rayOrigin = targetPositionWorld.clone();
rayOrigin.y += 1.5; // Start raycast safely above the potential target point
raycaster.set(rayOrigin, new THREE.Vector3(0, -1, 0)); // Ray pointing straight down
// Find intersections only with the ground mesh
const intersects = raycaster.intersectObject(groundMesh);
if (intersects.length > 0) {
// If the ray hits the ground, update the IK target's position to the hit point.
// This makes the leg adapt to the terrain height.
legTargetObject.position.copy(intersects[0].point);
} else {
// Optional: Handle cases where ground is not hit (e.g., gaps, edges).
// For this example, we'll just keep the leg in its last valid position if no ground is found.
// console.warn(`Leg ${i} raycast did not hit ground.`);
}
// --- Solve IK ---
// Solve the Inverse Kinematics for the leg chain.
// Call solve() on the IK object representing the *last* joint in the chain.
legData.ikChainBones[legData.ikChainBones.length - 1].ik.solve();
}
}
/**
* The main animation loop. Called recursively via requestAnimationFrame.
*/
function animate() {
requestAnimationFrame(animate); // Schedule the next frame
const deltaTime = clock.getDelta(); // Get time elapsed since the previous frame
// Update the spider's movement and leg animations
updateSpider(deltaTime);
// Update camera controls (handles damping, zooming, etc.)
controls.update();
// Render the scene from the camera's perspective
renderer.render(scene, camera);
}
// --- Initialize Application ---
init(); // Set up the scene and run initialization logic
animate(); // Start the animation loop
</script>
</body>
</html>