<!DOCTYPE html>
<html>
<head>
<title>Procedural Spider Animation with THREE.IK</title>
<style>
body { margin: 0; overflow: hidden; background-color: #222; font-family: Arial, sans-serif; color: white; }
canvas { display: block; }
#info { position: absolute; top: 10px; left: 10px; z-index: 100; }
</style>
</head>
<body>
<div id="info">
<h1>Procedural Spider Animation</h1>
<p>Controls: WASD to move, Mouse to orbit.</p>
<p>Legs adapt to terrain.</p>
</div>
<canvas id="myCanvas"></canvas>
<!-- Libraries -->
<!-- Three.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!-- THREE.IK -->
<script src="https://cdn.jsdelivr.net/npm/three-ik@0.1.0/dist/three-ik.min.js"></script>
<!-- THREE.OrbitControls (included with three.js r128, but good to reference path explicitly if needed) -->
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<script>
// --- Global Variables ---
let scene, camera, renderer;
let orbitControls;
let groundMesh;
let spider;
let keyboard = {}; // For input handling
// --- Spider Constants ---
const NUM_LEGS = 8;
const legSegments = 3; // hip, thigh, shin
const legRadius = 0.05;
const segmentLength = 0.5;
const totalLegLength = segmentLength * legSegments;
const spiderBodyRadius = 0.5;
const spiderMoveSpeed = 3; // Units per second
const spiderTurnSpeed = Math.PI; // Radians per second
// --- Gait Parameters ---
const gaitCycleDuration = 1.2; // seconds for one full cycle (all legs move)
const legLiftHeight = 0.2; // How high legs lift off ground
const legStepLength = 0.4; // Horizontal distance covered during swing phase
const legSupportOffset = 0.05; // Small backward offset for supporting legs
let gaitTime = 0; // Time elapsed in the gait cycle
// Leg groups for gait pattern (alternating sets of legs)
// Example for 8 legs: FL, MF1, MR2, BL move together, then FR, MR1, MF2, BR move together
const legGroups = [
[0, 2, 5, 6], // Group A: Front-Left, Mid-Front-Left, Mid-Rear-Right, Back-Left
[1, 3, 4, 7] // Group B: Front-Right, Mid-Front-Right, Mid-Rear-Left, Back-Right
];
let legTargets = []; // THREE.Object3D for each leg's IK target
let ikChains = []; // THREE.IK.IKChain for each leg
let legRoots = []; // THREE.Object3D for each leg's base mount point
// --- Initialization ---
function init() {
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x333333);
// Camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(5, 5, 5);
// Renderer
const canvas = document.getElementById('myCanvas');
renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(window.devicePixelRatio);
renderer.shadowMap.enabled = true;
// Lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.8);
dirLight.position.set(10, 10, 10);
dirLight.castShadow = true;
dirLight.shadow.mapSize.width = 2048;
dirLight.shadow.mapSize.height = 2048;
dirLight.shadow.camera.near = 0.5;
dirLight.shadow.camera.far = 50;
scene.add(dirLight);
// Controls
orbitControls = new THREE.OrbitControls(camera, renderer.domElement);
orbitControls.enableDamping = true;
orbitControls.dampingFactor = 0.1;
orbitControls.screenSpacePanning = false;
orbitControls.minDistance = 2;
orbitControls.maxDistance = 20;
orbitControls.maxPolarAngle = Math.PI / 2; // Prevent camera from going below ground
// Ground
createGround();
// Obstacles
createObstacles();
// Spider
createSpider();
// Event Listeners
window.addEventListener('resize', onWindowResize, false);
document.addEventListener('keydown', onKeyDown, false);
document.addEventListener('keyup', onKeyUp, false);
// Start animation loop
animate();
}
// --- Ground Creation ---
function createGround() {
const width = 25;
const height = 25;
const segments = 128; // Higher segments for smoother terrain
const geometry = new THREE.PlaneGeometry(width, height, segments - 1, segments - 1);
const vertices = geometry.attributes.position.array;
// Procedural Terrain Generation using combined sine waves for hills
for (let i = 0; i < vertices.length; i += 3) {
const x = vertices[i]; // X coordinate
const z = vertices[i + 2]; // Z coordinate (PlaneGeometry uses Y as vertical, but we use Z from its XY plane)
// Noise function: combining several sine waves with different frequencies and amplitudes
let noise = 0;
noise += Math.sin(x * 0.4 + z * 0.2) * 0.8;
noise += Math.sin(x * 0.7 - z * 0.5) * 0.5;
noise += Math.sin(x * 0.2 + z * 0.9) * 0.3;
noise = noise * 2.0; // Scale the overall height variation
// Clamp the height to create more reasonable terrain, preventing extreme cliffs
noise = Math.max(-2.5, Math.min(2.5, noise));
vertices[i + 1] = noise; // Set the Y position (height) of the vertex
}
geometry.attributes.position.needsUpdate = true;
geometry.computeVertexNormals(); // Recalculate normals for correct lighting
const material = new THREE.MeshStandardMaterial({ color: 0x808080, side: THREE.DoubleSide });
groundMesh = new THREE.Mesh(geometry, material);
groundMesh.rotation.x = -Math.PI / 2; // Rotate the plane to be horizontal
groundMesh.receiveShadow = true;
scene.add(groundMesh);
}
// --- Obstacle Creation ---
function createObstacles() {
const obstacleMaterial = new THREE.MeshStandardMaterial({ color: 0xaa0000 });
// Sphere obstacle 1
const sphereGeometry = new THREE.SphereGeometry(0.5, 32, 32);
const sphereMesh1 = new THREE.Mesh(sphereGeometry, obstacleMaterial);
sphereMesh1.position.set(5, 0.5, 3); // Position it on the terrain
sphereMesh1.castShadow = true;
scene.add(sphereMesh1);
// Box obstacle 1
const boxGeometry = new THREE.BoxGeometry(1, 1, 1);
const boxMesh1 = new THREE.Mesh(boxGeometry, obstacleMaterial);
boxMesh1.position.set(-4, 0.5, -2); // Position it on the terrain
boxMesh1.castShadow = true;
scene.add(boxMesh1);
// Sphere obstacle 2 (higher up)
const sphereMesh2 = new THREE.Mesh(sphereGeometry, obstacleMaterial);
sphereMesh2.position.set(0, 2.0, 6);
sphereMesh2.castShadow = true;
scene.add(sphereMesh2);
}
// --- Spider Creation ---
function createSpider() {
spider = new THREE.Group(); // Use a Group to hold all spider parts
scene.add(spider);
// Spider Body
const bodyGeometry = new THREE.SphereGeometry(spiderBodyRadius, 32, 16);
const bodyMaterial = new THREE.MeshStandardMaterial({ color: 0x222222 });
const bodyMesh = new THREE.Mesh(bodyGeometry, bodyMaterial);
bodyMesh.position.y = spiderBodyRadius; // Center body base slightly above ground
bodyMesh.castShadow = true;
spider.add(bodyMesh);
// Leg Placement relative to the spider's body center
const legMountPositions = [
// Front Pair
{ x: spiderBodyRadius * 0.8, z: spiderBodyRadius * 0.6 }, // 0: Front-Left
{ x: -spiderBodyRadius * 0.8, z: spiderBodyRadius * 0.6 }, // 1: Front-Right
// Middle Pair 1
{ x: spiderBodyRadius * 1.0, z: 0 }, // 2: MidLeft 1
{ x: -spiderBodyRadius * 1.0, z: 0 }, // 3: MidRight 1
// Middle Pair 2
{ x: spiderBodyRadius * 1.0, z: -0.2 }, // 4: MidLeft 2 (slightly back)
{ x: -spiderBodyRadius * 1.0, z: -0.2 }, // 5: MidRight 2 (slightly back)
// Rear Pair
{ x: spiderBodyRadius * 0.8, z: -spiderBodyRadius * 0.6 }, // 6: Back-Left
{ x: -spiderBodyRadius * 0.8, z: -spiderBodyRadius * 0.6 } // 7: Back-Right
];
legRoots = [];
legTargets = [];
ikChains = [];
for (let i = 0; i < NUM_LEGS; i++) {
const legMountPos = legMountPositions[i];
// Create a root group for each leg to manage its position and orientation
const legRoot = new THREE.Group();
legRoot.position.set(legMountPos.x, spiderBodyRadius * 0.8, legMountPos.z); // Position leg mount point
spider.add(legRoot);
legRoots.push(legRoot);
// --- IK Chain Setup ---
const chain = new THREE.IK.IKChain();
chain.loop = true; // Allow looping for solvers
// --- Leg Bones ---
// Hip Bone: Parented to the leg root group. Its forward axis will effectively point downwards.
const hipBone = new THREE.Bone();
hipBone.name = `leg${i}_hip`;
legRoot.add(hipBone); // Hip bone starts at the legRoot group's origin
chain.add(hipBone, { constraints: [new THREE.IKConstraint.BALL()] });
// Thigh Bone: Parented to Hip Bone, extends downwards.
const thighBone = new THREE.Bone();
thighBone.position.set(0, -segmentLength, 0); // Position relative to parent bone (hip)
thighBone.name = `leg${i}_thigh`;
hipBone.add(thighBone);
chain.add(thighBone, { constraints: [new THREE.IKConstraint.BALL()] });
// Shin Bone (Effector): Parented to Thigh Bone, extends downwards.
const shinBone = new THREE.Bone();
shinBone.position.set(0, -segmentLength, 0); // Position relative to parent bone (thigh)
shinBone.name = `leg${i}_shin`;
thighBone.add(shinBone);
chain.add(shinBone, { constraints: [new THREE.IKConstraint.BALL()] }); // Add constraints to the effector bone
chain.setEffector(shinBone); // Mark the shin bone as the effector
// --- Visual Meshes for Leg Segments ---
const legBoneMaterial = new THREE.MeshStandardMaterial({ color: 0x444444 });
// Hip Visual (Sphere)
const hipMesh = new THREE.Mesh(new THREE.SphereGeometry(legRadius * 1.5, 16, 8), legBoneMaterial);
hipMesh.position.set(0, 0, 0); // Positioned at the hip bone's origin
hipBone.add(hipMesh);
// Thigh Visual (Cylinder)
const thighMesh = new THREE.Mesh(new THREE.CylinderGeometry(legRadius, legRadius, segmentLength, 16), legBoneMaterial);
thighMesh.position.set(0, -segmentLength / 2, 0); // Center the cylinder along the bone axis
thighMesh.rotation.x = Math.PI / 2; // Align cylinder's default Z-axis with bone's forward axis (-Y)
thighBone.add(thighMesh);
// Shin Visual (Cylinder)
const shinMesh = new THREE.Mesh(new THREE.CylinderGeometry(legRadius * 0.8, legRadius * 0.6, segmentLength, 16), legBoneMaterial);
shinMesh.position.set(0, -segmentLength / 2, 0); // Center the cylinder along the bone axis
shinMesh.rotation.x = Math.PI / 2; // Align cylinder with bone's forward axis
shinBone.add(shinMesh);
shinMesh.castShadow = true;
// --- IK Target ---
const target = new THREE.Object3D();
target.name = `leg${i}_target`;
// Calculate initial target position: leg extended straight down
let initialLegWorldPos = new THREE.Vector3();
legRoot.getWorldPosition(initialLegWorldPos); // Get world position of the leg's mounting point
initialLegWorldPos.y -= totalLegLength; // Extend leg downwards by its total length
target.position.copy(initialLegWorldPos);
scene.add(target); // Add target to scene for potential debugging/visibility
legTargets.push(target);
ikChains.push(chain);
}
}
// --- Input Handling ---
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function onKeyDown(event) {
keyboard[event.key.toLowerCase()] = true;
}
function onKeyUp(event) {
keyboard[event.key.toLowerCase()] = false;
}
// --- Animation Loop ---
let lastTime = 0;
function animate(currentTime = 0) {
const deltaTime = (currentTime - lastTime) / 1000; // Time elapsed in seconds
lastTime = currentTime;
// Update OrbitControls
orbitControls.update();
// Handle Spider Movement based on Keyboard Input
const moveDir = new THREE.Vector3();
if (keyboard['w']) {
moveDir.z -= 1; // Move forward
}
if (keyboard['s']) {
moveDir.z += 1; // Move backward
}
if (keyboard['a']) {
spider.rotation.y += spiderTurnSpeed * deltaTime; // Turn left
}
if (keyboard['d']) {
spider.rotation.y -= spiderTurnSpeed * deltaTime; // Turn right
}
// Normalize and apply movement vector, respecting spider's orientation
if (moveDir.length() > 0) {
moveDir.normalize();
// Apply rotation to movement direction
const forward = new THREE.Vector3(0, 0, -1).applyQuaternion(spider.quaternion);
const right = new THREE.Vector3(1, 0, 0).applyQuaternion(spider.quaternion);
spider.position.add(forward.multiplyScalar(moveDir.z * spiderMoveSpeed * deltaTime));
spider.position.add(right.multiplyScalar(moveDir.x * spiderMoveSpeed * deltaTime)); // Currently moveDir.x is 0, but could be used for strafing
}
// Update Spider Leg Gait and IK Targets
updateSpiderLegs(deltaTime);
// Solve IK chains for all legs
for (let i = 0; i < ikChains.length; i++) {
ikChains[i].solve();
}
// Render the scene
renderer.render(scene, camera);
// Request next frame
requestAnimationFrame(animate);
}
// --- Spider Gait and IK Target Logic ---
function updateSpiderLegs(deltaTime) {
gaitTime += deltaTime;
const phase = (gaitTime / gaitCycleDuration) % 1.0; // Progress through the gait cycle (0.0 to 1.0)
// Determine which leg groups are swinging vs supporting
const group1Swinging = phase < 0.5; // Group 1 legs swing during the first half of the cycle
const group2Swinging = phase >= 0.5; // Group 2 legs swing during the second half
for (let i = 0; i < NUM_LEGS; i++) {
const legRoot = legRoots[i];
const legTarget = legTargets[i];
// Calculate the desired ground contact point using raycasting
const rayOrigin = legRoot.position.clone(); // Start ray from leg root's position relative to spider
rayOrigin.y += 2.0; // Elevate the ray origin to ensure it hits terrain even if leg is short
const raycaster = new THREE.Raycaster();
raycaster.set(rayOrigin, new THREE.Vector3(0, -1, 0)); // Raycast straight down
const intersects = raycaster.intersectObject(groundMesh);
let desiredGroundPoint = new THREE.Vector3();
if (intersects.length > 0) {
desiredGroundPoint.copy(intersects[0].point); // Use the intersection point on the ground
} else {
// Fallback: if no ground found, extend leg straight down from its mount
desiredGroundPoint.copy(legRoot.position);
desiredGroundPoint.y -= totalLegLength;
}
// --- Apply Gait Movement to Target Position ---
const isLegInGroup1 = legGroups[0].includes(i);
const isLegInGroup2 = legGroups[1].includes(i);
let swingAmount = 0;
let isSwinging = false;
if (isLegInGroup1) {
if (group1Swinging) { // Leg is swinging
const swingPhase = (phase / 0.5); // Normalize phase within the swing period (0.0 to 1.0)
swingAmount = Math.sin(swingPhase * Math.PI) * legStepLength; // Smooth sine wave for forward motion
isSwinging = true;
} else { // Leg is supporting
// Keep leg planted, add slight backward offset for stability
swingAmount = -legSupportOffset;
}
} else if (isLegInGroup2) {
if (group2Swinging) { // Leg is swinging
const swingPhase = ((phase - 0.5) / 0.5); // Normalize phase within the swing period (0.0 to 1.0)
swingAmount = Math.sin(swingPhase * Math.PI) * legStepLength; // Smooth sine wave for forward motion
isSwinging = true;
} else { // Leg is supporting
// Keep leg planted, add slight backward offset for stability
swingAmount = -legSupportOffset;
}
}
// Calculate the final target position based on ground point, swing, and lift
legTarget.position.copy(desiredGroundPoint);
// Apply forward/backward swing relative to the spider's orientation
const spiderForward = new THREE.Vector3(0, 0, -1).applyQuaternion(spider.quaternion);
legTarget.position.add(spiderForward.multiplyScalar(swingAmount));
// Apply upward lift during the swing phase
if (isSwinging) {
// Calculate the lift height based on the swing phase progress
const swingPhase = isLegInGroup1 ? (phase / 0.5) : ((phase - 0.5) / 0.5);
const liftHeight = Math.sin(swingPhase * Math.PI) * legLiftHeight; // Max lift in the middle of the swing
legTarget.position.y += liftHeight;
}
}
}
// --- Start the Application ---
init();
</script>
</body>
</html>