Interactive 3D Spider Animation with Three.js
Here's a complete HTML file that implements an interactive 3D spider animation with procedural leg movement using Three.js and THREE.IK:
<!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</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-color: rgba(0,0,0,0.5);
padding: 10px;
border-radius: 5px;
font-size: 14px;
}
</style>
</head>
<body>
<div id="info">
<strong>Controls:</strong><br>
W/A/S/D: Move spider<br>
Mouse: Orbit camera<br>
Click: Toggle spider movement
</div>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/build/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.132.2/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>
// Scene setup
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x888888);
// Camera setup
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 5, 10);
// Renderer setup
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
// Controls
const controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.dampingFactor = 0.05;
// Lighting
const ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(1, 1, 1);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 1024;
directionalLight.shadow.mapSize.height = 1024;
scene.add(directionalLight);
// Ground with height variation
const groundGeometry = new THREE.PlaneGeometry(50, 50, 100, 100);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x3a5f0b,
side: THREE.DoubleSide,
flatShading: true
});
// Create height variation
const groundVertices = groundGeometry.attributes.position;
for (let i = 0; i < groundVertices.count; i++) {
const x = groundVertices.getX(i);
const z = groundVertices.getZ(i);
// Simple noise function for height variation
const height = Math.sin(x * 0.2) * Math.cos(z * 0.2) * 1.5;
groundVertices.setY(i, height);
}
groundGeometry.computeVertexNormals();
const ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
// Add some obstacles
const obstacleGeometry = new THREE.BoxGeometry(1, 1, 1);
const obstacleMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513 });
for (let i = 0; i < 10; i++) {
const obstacle = new THREE.Mesh(obstacleGeometry, obstacleMaterial);
obstacle.position.set(
Math.random() * 40 - 20,
0.5,
Math.random() * 40 - 20
);
obstacle.castShadow = true;
obstacle.receiveShadow = true;
scene.add(obstacle);
}
// Spider class
class Spider {
constructor() {
this.group = new THREE.Group();
this.group.position.y = 0.5;
scene.add(this.group);
// Body
const bodyGeometry = new THREE.SphereGeometry(0.5, 16, 16);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x333333,
roughness: 0.8
});
this.body = new THREE.Mesh(bodyGeometry, bodyMaterial);
this.body.castShadow = true;
this.group.add(this.body);
// Leg parameters
this.legLengths = [0.3, 0.4, 0.5]; // Three segments per leg
this.legs = [];
this.ikSolvers = [];
this.legTargets = [];
this.legBasePositions = [
// Front left legs
{ x: -0.3, y: 0, z: 0.4 },
{ x: -0.4, y: 0, z: 0.3 },
// Middle left legs
{ x: -0.5, y: 0, z: 0.1 },
{ x: -0.4, y: 0, z: -0.1 },
// Back left legs
{ x: -0.3, y: 0, z: -0.3 },
{ x: -0.2, y: 0, z: -0.4 },
// Front right legs
{ x: 0.3, y: 0, z: 0.4 },
{ x: 0.4, y: 0, z: 0.3 },
// Middle right legs
{ x: 0.5, y: 0, z: 0.1 },
{ x: 0.4, y: 0, z: -0.1 },
// Back right legs
{ x: 0.3, y: 0, z: -0.3 },
{ x: 0.2, y: 0, z: -0.4 }
];
// Create legs
for (let i = 0; i < 8; i++) {
this.createLeg(i);
}
// Movement parameters
this.speed = 0.05;
this.direction = new THREE.Vector3(0, 0, 0);
this.isMoving = false;
this.stepHeight = 0.2;
this.stepOffset = Math.PI / 4; // Offset between legs
this.time = 0;
this.raycaster = new THREE.Raycaster();
this.raycaster.far = 2;
}
createLeg(legIndex) {
const legGroup = new THREE.Group();
this.group.add(legGroup);
// Position the leg base
const basePos = this.legBasePositions[legIndex];
legGroup.position.set(basePos.x, basePos.y, basePos.z);
// Create leg segments
const legSegments = [];
let currentPosition = new THREE.Vector3(0, 0, 0);
for (let i = 0; i < this.legLengths.length; i++) {
const segmentLength = this.legLengths[i];
const segmentGeometry = new THREE.CylinderGeometry(0.05, 0.05, segmentLength, 8);
const segmentMaterial = new THREE.MeshStandardMaterial({
color: 0x555555,
roughness: 0.7
});
const segment = new THREE.Mesh(segmentGeometry, segmentMaterial);
// Position the segment
segment.position.copy(currentPosition);
segment.position.y -= segmentLength / 2;
segment.rotation.z = Math.PI / 2;
// Add to leg group
legGroup.add(segment);
legSegments.push(segment);
// Update current position for next segment
currentPosition.y -= segmentLength;
}
// Create IK solver
const ikSolver = new THREE.IK({
target: new THREE.Vector3(0, -1, 0),
effector: legSegments[legSegments.length - 1],
links: [
{
joint: legGroup,
length: this.legLengths[0],
rotationMin: -Math.PI / 2,
rotationMax: Math.PI / 2
},
{
joint: legSegments[0],
length: this.legLengths[1],
rotationMin: -Math.PI / 2,
rotationMax: Math.PI / 2
},
{
joint: legSegments[1],
length: this.legLengths[2],
rotationMin: -Math.PI / 2,
rotationMax: Math.PI / 2
}
]
});
// Create target for IK
const target = new THREE.Mesh(
new THREE.SphereGeometry(0.05, 8, 8),
new THREE.MeshBasicMaterial({ color: 0xff0000 })
);
target.position.copy(ikSolver.target);
legGroup.add(target);
this.legs.push(legGroup);
this.ikSolvers.push(ikSolver);
this.legTargets.push(target);
}
update(deltaTime) {
this.time += deltaTime;
// Update spider position based on direction
if (this.isMoving) {
const moveVector = this.direction.clone().multiplyScalar(this.speed);
this.group.position.add(moveVector);
// Rotate spider to face movement direction
if (moveVector.length() > 0) {
const targetQuaternion = new THREE.Quaternion();
targetQuaternion.setFromUnitVectors(
new THREE.Vector3(0, 0, 1),
moveVector.clone().normalize()
);
this.group.quaternion.slerp(targetQuaternion, 0.1);
}
}
// Update leg targets based on movement
for (let i = 0; i < this.legs.length; i++) {
const leg = this.legs[i];
const ikSolver = this.ikSolvers[i];
const target = this.legTargets[i];
// Calculate target position based on movement
const legPhase = (this.time + i * this.stepOffset) % (Math.PI * 2);
const legPhaseValue = Math.sin(legPhase);
// Calculate target position in local space
const localTarget = new THREE.Vector3();
localTarget.copy(ikSolver.target);
if (this.isMoving) {
// Lift leg during movement
localTarget.y = -this.legLengths.reduce((a, b) => a + b, 0) * 0.8 +
Math.sin(legPhase) * this.stepHeight;
// Move leg forward/backward based on phase
localTarget.z = Math.cos(legPhase) * 0.3;
} else {
// Default position when not moving
localTarget.y = -this.legLengths.reduce((a, b) => a + b, 0);
}
// Convert to world space
const worldTarget = leg.localToWorld(localTarget.clone());
// Raycast to find ground height
this.raycaster.set(worldTarget, new THREE.Vector3(0, -1, 0));
const intersects = this.raycaster.intersectObject(ground);
if (intersects.length > 0) {
// Adjust target to ground height
const groundHeight = intersects[0].point.y;
worldTarget.y = groundHeight;
}
// Convert back to local space
const adjustedTarget = leg.worldToLocal(worldTarget.clone());
// Update IK target
ikSolver.target.copy(adjustedTarget);
target.position.copy(adjustedTarget);
// Update IK solver
ikSolver.update();
}
}
setDirection(x, z) {
this.direction.set(x, 0, z).normalize();
}
toggleMovement() {
this.isMoving = !this.isMoving;
}
}
// Create spider
const spider = new Spider();
// Handle window resize
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
// Handle keyboard input
const keys = {
w: false,
a: false,
s: false,
d: false
};
window.addEventListener('keydown', (e) => {
if (e.key.toLowerCase() in keys) {
keys[e.key.toLowerCase()] = true;
}
});
window.addEventListener('keyup', (e) => {
if (e.key.toLowerCase() in keys) {
keys[e.key.toLowerCase()] = false;
}
});
// Handle mouse click to toggle movement
window.addEventListener('click', () => {
spider.toggleMovement();
});
// Animation loop
let lastTime = 0;
function animate(currentTime) {
requestAnimationFrame(animate);
const deltaTime = (currentTime - lastTime) / 1000;
lastTime = currentTime;
// Update spider direction based on keys
let x = 0, z = 0;
if (keys.w) z -= 1;
if (keys.s) z += 1;
if (keys.a) x -= 1;
if (keys.d) x += 1;
spider.setDirection(x, z);
// Update spider
spider.update(deltaTime);
// Update controls
controls.update();
// Render scene
renderer.render(scene, camera);
}
animate(0);
</script>
</body>
</html>
Features Implemented:
-
Procedural Spider Animation:
- Spider model with a body and eight multi-jointed legs
- Each leg has three segments with IK (Inverse Kinematics) for realistic movement
- Legs automatically adapt to the terrain height using raycasting
-
User Controls:
- W/A/S/D keys to control spider movement direction
- Mouse-controlled orbital camera to view from any angle
- Click to toggle spider movement on/off
-
Test Environment:
- Non-flat ground plane with height variation (hills and valleys)
- Randomly scattered obstacles (boxes) on the terrain
-
Visual Enhancements:
- Proper lighting with shadows
- Realistic materials for the spider and environment
- Informational overlay with controls
The spider's legs will automatically adjust to the terrain as it moves, demonstrating the procedural animation system. The IK solvers ensure that the legs bend realistically to reach their target positions on the ground.