I'll create a unified HTML file with a Three.js application featuring a procedurally animated spider that adapts to terrain using THREE.IK. Here's the implementation:
<!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</title>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
#info {
position: absolute;
top: 10px;
width: 100%;
text-align: center;
color: white;
font-family: Arial, sans-serif;
pointer-events: none;
}
</style>
</head>
<body>
<div id="info">
Controls: W,A,S,D to move | Mouse to rotate camera | Mouse wheel to zoom
</div>
<script src="https://cdn.jsdelivr.net/npm/three@0.137.0/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.137.0/examples/js/controls/OrbitControls.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three-ik@0.1.0/build/three-ik.min.js"></script>
<script>
// Main variables
let scene, camera, renderer, controls;
let terrain, spider;
let clock = new THREE.Clock();
let ikSolver;
// Spider properties
const SPIDER = {
bodyRadius: 1,
bodyHeight: 0.6,
legCount: 8,
legSegments: 3,
legLength: 3,
stepHeight: 0.5,
moveSpeed: 5,
turnSpeed: 2,
legSpread: 2.2
};
// Movement controls
const keys = {
w: false,
a: false,
s: false,
d: false
};
// Spider leg management
let legs = [];
let legTargets = [];
let legMoving = [];
let legPhases = [];
// Initialize the application
init();
animate();
function init() {
// Create scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x87CEEB);
// Add lighting
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(5, 10, 7);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
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 camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 10, 15);
// Create renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
// Add orbit controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// Create terrain
createTerrain();
// Create spider
createSpider();
// Initialize IK solver
ikSolver = new THREE.IK();
// Set up leg IK chains
setupLegs();
// Add event listeners
window.addEventListener('resize', onWindowResize);
document.addEventListener('keydown', onKeyDown);
document.addEventListener('keyup', onKeyUp);
}
function createTerrain() {
// Create terrain geometry
const geometry = new THREE.PlaneGeometry(50, 50, 64, 64);
// Apply height map to terrain
const vertices = geometry.attributes.position.array;
for (let i = 0; i < vertices.length; i += 3) {
const x = vertices[i];
const z = vertices[i + 2];
// Generate varied heights using simplex noise approximation
vertices[i + 1] = Math.sin(x * 0.3) * Math.cos(z * 0.3) * 1.5;
}
geometry.computeVertexNormals();
// Create terrain material
const material = new THREE.MeshStandardMaterial({
color: 0x4b7446,
flatShading: false,
wireframe: false
});
// Create terrain mesh
terrain = new THREE.Mesh(geometry, material);
terrain.rotation.x = -Math.PI / 2;
terrain.receiveShadow = true;
scene.add(terrain);
// Add some obstacles
addObstacles();
}
function addObstacles() {
// Add random obstacles to the terrain
for (let i = 0; i < 10; i++) {
const type = Math.random() > 0.5 ? 'box' : 'sphere';
const size = 0.5 + Math.random() * 1.5;
let geometry;
if (type === 'box') {
geometry = new THREE.BoxGeometry(size, size, size);
} else {
geometry = new THREE.SphereGeometry(size, 16, 16);
}
const material = new THREE.MeshStandardMaterial({
color: 0x8B4513,
roughness: 0.8
});
const obstacle = new THREE.Mesh(geometry, material);
// Position obstacle on terrain
const x = (Math.random() - 0.5) * 40;
const z = (Math.random() - 0.5) * 40;
const y = getTerrainHeight(x, z) + size / 2;
obstacle.position.set(x, y, z);
obstacle.castShadow = true;
obstacle.receiveShadow = true;
scene.add(obstacle);
}
}
function createSpider() {
// Create spider group
spider = new THREE.Group();
// Create spider body
const bodyGeometry = new THREE.SphereGeometry(SPIDER.bodyRadius, 16, 16);
bodyGeometry.scale(1, SPIDER.bodyHeight / SPIDER.bodyRadius, 1.3);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x222222,
roughness: 0.7
});
const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
body.castShadow = true;
spider.add(body);
// Position spider above terrain
spider.position.y = getTerrainHeight(0, 0) + SPIDER.bodyRadius * SPIDER.bodyHeight + 1;
scene.add(spider);
}
function setupLegs() {
// Create legs with IK chains
for (let i = 0; i < SPIDER.legCount; i++) {
// Calculate leg angle around body
const angle = (i / SPIDER.legCount) * Math.PI * 2;
const legGroup = new THREE.Group();
// Alternate leg phases for natural walking
legPhases[i] = i % 2 === 0 ? 0 : Math.PI;
legMoving[i] = false;
// Create leg segments
const segments = [];
let totalLength = 0;
for (let j = 0; j < SPIDER.legSegments; j++) {
const segmentLength = SPIDER.legLength / SPIDER.legSegments;
totalLength += segmentLength;
const segmentGeometry = new THREE.CylinderGeometry(
0.15 - j * 0.03, 0.12 - j * 0.03,
segmentLength, 8
);
// Offset to align with next segment
segmentGeometry.translate(0, segmentLength / 2, 0);
const segmentMaterial = new THREE.MeshStandardMaterial({
color: 0x111111,
roughness: 0.7
});
const segment = new THREE.Mesh(segmentGeometry, segmentMaterial);
segment.castShadow = true;
if (j === 0) {
// Position first segment at spider body
const xPos = Math.cos(angle) * SPIDER.bodyRadius * 0.9;
const zPos = Math.sin(angle) * SPIDER.bodyRadius * 0.9;
segment.position.set(xPos, 0, zPos);
// Rotate segment outward from body
segment.rotation.z = Math.PI / 2 - angle;
legGroup.add(segment);
} else {
// Connect to previous segment
const prevSegment = segments[j - 1];
const prevLength = SPIDER.legLength / SPIDER.legSegments;
segment.position.y = prevLength;
prevSegment.add(segment);
// Add joint bend for natural leg shape
if (j === 1) {
segment.rotation.x = -Math.PI / 4;
} else if (j === 2) {
segment.rotation.x = -Math.PI / 3;
}
}
segments.push(segment);
}
// Create IK chain for this leg
const chain = new THREE.IKChain();
const constraints = [];
// Add constraints for each joint
for (let j = 0; j < segments.length; j++) {
const constraint = new THREE.IKJoint(
segments[j],
{
x: j === 0 ? Math.PI / 4 : Math.PI / 2,
y: j === 0 ? Math.PI / 4 : Math.PI / 8,
z: j === 0 ? Math.PI / 4 : Math.PI / 8
}
);
constraints.push(constraint);
chain.add(constraint);
}
// Create target for IK
const targetGeometry = new THREE.SphereGeometry(0.1, 8, 8);
const targetMaterial = new THREE.MeshBasicMaterial({
color: 0xff0000,
visible: false
});
const target = new THREE.Mesh(targetGeometry, targetMaterial);
// Position target at rest position
const restX = Math.cos(angle) * SPIDER.legSpread;
const restZ = Math.sin(angle) * SPIDER.legSpread;
const restY = -SPIDER.bodyRadius * SPIDER.bodyHeight;
target.position.set(
spider.position.x + restX,
spider.position.y + restY,
spider.position.z + restZ
);
scene.add(target);
// Set up IK solver for this leg
const ik = new THREE.IK();
ik.add(chain, target);
// Store references
legs.push({
group: legGroup,
segments: segments,
ik: ik,
angle: angle,
restPosition: new THREE.Vector3(restX, restY, restZ)
});
legTargets.push(target);
spider.add(legGroup);
}
}
function animate() {
requestAnimationFrame(animate);
const delta = clock.getDelta();
// Update spider movement
updateSpiderMovement(delta);
// Update leg positions and IK
updateLegs(delta);
// Update controls
controls.update();
// Render scene
renderer.render(scene, camera);
}
function updateSpiderMovement(delta) {
// Calculate movement direction
let moveX = 0;
let moveZ = 0;
if (keys.w) moveZ -= 1;
if (keys.s) moveZ += 1;
if (keys.a) moveX -= 1;
if (keys.d) moveX += 1;
// Normalize for diagonal movement
if (moveX !== 0 && moveZ !== 0) {
moveX *= 0.7071; // 1/sqrt(2)
moveZ *= 0.7071;
}
// Apply movement in spider's local space
if (moveX !== 0 || moveZ !== 0) {
// Rotate spider
if (moveX !== 0) {
spider.rotation.y += moveX * SPIDER.turnSpeed * delta;
}
// Move forward/backward
if (moveZ !== 0) {
const moveVec = new THREE.Vector3(0, 0, moveZ * SPIDER.moveSpeed * delta);
moveVec.applyQuaternion(spider.quaternion);
spider.position.x += moveVec.x;
spider.position.z += moveVec.z;
// Adjust height based on terrain
const terrainY = getTerrainHeight(spider.position.x, spider.position.z);
spider.position.y = terrainY + SPIDER.bodyRadius * SPIDER.bodyHeight + 1;
// Align to terrain normal (simplified)
const normal = getTerrainNormal(spider.position.x, spider.position.z);
const targetRotation = new THREE.Quaternion().setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
normal
);
spider.quaternion.slerp(targetRotation, 0.1);
}
}
}
function updateLegs(delta) {
// Update each leg
for (let i = 0; i < legs.length; i++) {
const leg = legs[i];
const target = legTargets[i];
// Calculate ideal foot position in world space
const idealPos = new THREE.Vector3();
idealPos.copy(leg.restPosition);
idealPos.applyQuaternion(spider.quaternion);
idealPos.add(spider.position);
// Current target position
const currentPos = target.position.clone();
// Distance between current and ideal position
const distance = currentPos.distanceTo(idealPos);
// Check if leg needs to move (step)
if (!legMoving[i] && distance > SPIDER.legLength * 0.5) {
legMoving[i] = true;
}