Procedural Spider Animation using Three.js and THREE.IK
Overview
This project creates an interactive 3D web application using Three.js to demonstrate advanced procedural spider animation using THREE.IK. The application features a spider model with procedurally animated legs that adapt to the ground beneath them. The user can control the spider's movement direction using keyboard inputs and view the spider from any angle using a mouse-controlled orbital camera.
Code
<!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;
background-color: #f0f0f0;
font-family: Monospace;
font-size: 13px;
line-height: 24px;
overscroll-behavior: none;
text-rendering: optimizeLegibility;
user-select: none;
}
#canvas {
width: 100%;
height: 100vh;
display: block;
}
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three-ik@0.1.0/build/three-ik.min.js"></script>
<script>
// Set up the scene, camera, and renderer
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({
canvas: document.createElement('canvas'),
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.domElement.id = 'canvas';
// Create the ground plane with varied heights
const groundGeometry = new THREE.PlaneGeometry(100, 100, 100, 100);
const groundMaterial = new THREE.MeshLambertMaterial({ color: 0xffffff });
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
for (let i = 0; i < groundGeometry.attributes.position.count; i++) {
const x = groundGeometry.attributes.position.getX(i);
const z = groundGeometry.attributes.position.getZ(i);
const y = Math.sin(x * 0.1) * Math.cos(z * 0.1) * 5;
groundGeometry.attributes.position.setY(i, y);
}
groundGeometry.computeVertexNormals();
scene.add(ground);
// Scatter a few basic obstacles on the terrain
for (let i = 0; i < 10; i++) {
const obstacleGeometry = new THREE.SphereGeometry(1, 32, 32);
const obstacleMaterial = new THREE.MeshLambertMaterial({ color: 0xff0000 });
const obstacle = new THREE.Mesh(obstacleGeometry, obstacleMaterial);
obstacle.position.x = Math.random() * 50 - 25;
obstacle.position.z = Math.random() * 50 - 25;
obstacle.position.y = 5 + Math.random() * 5;
scene.add(obstacle);
}
// Create the spider model
const spiderBodyGeometry = new THREE.SphereGeometry(2, 32, 32);
const spiderBodyMaterial = new THREE.MeshLambertMaterial({ color: 0x0000ff });
const spiderBody = new THREE.Mesh(spiderBodyGeometry, spiderBodyMaterial);
scene.add(spiderBody);
const spiderLegs = [];
for (let i = 0; i < 8; i++) {
const leg = new THREE.IK();
const effector = new THREE.IKEffector();
const legBones = [];
for (let j = 0; j < 3; j++) {
const boneGeometry = new THREE.SphereGeometry(0.5, 32, 32);
const boneMaterial = new THREE.MeshLambertMaterial({ color: 0x00ff00 });
const bone = new THREE.Mesh(boneGeometry, boneMaterial);
scene.add(bone);
legBones.push(bone);
const ikJoint = new THREE.IKJoint(bone);
if (j > 0) {
ikJoint.setParent(legBones[j - 1]);
}
leg.add(ikJoint);
}
effector.setPosition(new THREE.Vector3(0, 0, 0));
leg.add(effector);
spiderLegs.push({ leg, effector, bones: legBones });
scene.add(legBones[0]);
}
// Initialize the spider's position and legs
spiderBody.position.y = 10;
for (let i = 0; i < spiderLegs.length; i++) {
const angle = i * Math.PI / 4;
const leg = spiderLegs[i];
leg.bones[0].position.x = Math.cos(angle) * 2;
leg.bones[0].position.z = Math.sin(angle) * 2;
leg.bones[0].position.y = 0;
leg.effector.setPosition(new THREE.Vector3(0, -5, 0));
}
// Set up the camera controls
const cameraControls = new THREE.OrbitControls(camera, renderer.domElement);
camera.position.y = 20;
camera.position.z = 20;
// Set up the keyboard controls
const keyboardControls = {
w: false,
a: false,
s: false,
d: false
};
document.addEventListener('keydown', (event) => {
switch (event.key) {
case 'w':
keyboardControls.w = true;
break;
case 'a':
keyboardControls.a = true;
break;
case 's':
keyboardControls.s = true;
break;
case 'd':
keyboardControls.d = true;
break;
}
});
document.addEventListener('keyup', (event) => {
switch (event.key) {
case 'w':
keyboardControls.w = false;
break;
case 'a':
keyboardControls.a = false;
break;
case 's':
keyboardControls.s = false;
break;
case 'd':
keyboardControls.d = false;
break;
}
});
// Animate the scene
function animate() {
requestAnimationFrame(animate);
// Update the spider's position based on keyboard controls
if (keyboardControls.w) {
spiderBody.position.z -= 0.1;
for (let i = 0; i < spiderLegs.length; i++) {
spiderLegs[i].bones[0].position.z -= 0.1;
}
}
if (keyboardControls.s) {
spiderBody.position.z += 0.1;
for (let i = 0; i < spiderLegs.length; i++) {
spiderLegs[i].bones[0].position.z += 0.1;
}
}
if (keyboardControls.a) {
spiderBody.position.x -= 0.1;
for (let i = 0; i < spiderLegs.length; i++) {
spiderLegs[i].bones[0].position.x -= 0.1;
}
}
if (keyboardControls.d) {
spiderBody.position.x += 0.1;
for (let i = 0; i < spiderLegs.length; i++) {
spiderLegs[i].bones[0].position.x += 0.1;
}
}
// Update the spider's legs
for (let i = 0; i < spiderLegs.length; i++) {
const leg = spiderLegs[i];
const raycaster = new THREE.Raycaster();
raycaster.set(leg.bones[0].position, new THREE.Vector3(0, -1, 0));
const intersects = raycaster.intersectObject(ground);
if (intersects.length > 0) {
leg.effector.setPosition(new THREE.Vector3(0, intersects[0].distance, 0));
}
leg.leg.solver.update();
for (let j = 1; j < leg.bones.length; j++) {
leg.bones[j].position.copy(leg.bones[j - 1].position);
leg.bones[j].position.add(leg.leg.getJoint(j - 1).getRotation().apply(new THREE.Vector3(0, 1, 0)).multiplyScalar(1));
}
}
// Update the camera controls
cameraControls.update();
// Render the scene
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
Explanation
This code creates a 3D scene with a spider model and a ground plane. The spider has eight legs that are animated procedurally using THREE.IK. The user can control the spider's movement direction using the W, A, S, and D keys, and view the spider from any angle using the mouse-controlled orbital camera.
The ground plane is created with varied heights to test the spider's leg animation. A few basic obstacles are scattered on the terrain to add complexity to the scene.
The spider's legs are updated based on the ground plane's height beneath them, and