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.
Below is an all-in-one HTML file that creates a simple Three.js scene with a procedurally animated spider using THREE.IK. In this example the spider is built as a body with eight legs (each leg built from a three‐bone IK chain) and its feet “search” for the ground (whose height varies with a sine–cosine function) as the spider moves using WASD controls. You can orbit the camera with your mouse. The scene also includes a deformed ground plane (with hills and valleys) plus a few random obstacles. (This is a simplified “proof‐of‐concept” implementation that you can extend further.)
Simply save the code below as an HTML file and open it in your browser.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Procedural Spider Animation with THREE.IK</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
#info {
position: absolute;
top: 10px;
left: 10px;
color: #fff;
font-family: sans-serif;
z-index: 100;
}
</style>
</head>
<body>
<div id="info">
<p>
WASD keys to move the spider. Use mouse to orbit the camera.
</p>
</div>
<!-- Three.js -->
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/build/three.min.js"></script>
<!-- OrbitControls -->
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script>
<!-- THREE.IK -->
<script src="https://cdn.jsdelivr.net/npm/three-ik@0.1.0/build/three-ik.min.js"></script>
<script>
let scene, camera, renderer, controls;
let spider, spiderSpeed = 0.05;
let keyboard = {};
const legSystems = []; // Array to store each leg system data
init();
animate();
function init() {
// Scene
scene = new THREE.Scene();
scene.background = new THREE.Color(0x202020);
// Camera
camera = new THREE.PerspectiveCamera(
60,
window.innerWidth / window.innerHeight,
0.1,
1000
);
camera.position.set(20, 15, 20);
// Renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Orbit Controls
controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.target.set(0, 0, 0);
// Lights
const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
scene.add(ambientLight);
const dirLight = new THREE.DirectionalLight(0xffffff, 0.6);
dirLight.position.set(10, 20, 10);
scene.add(dirLight);
// Ground
const ground = createGround();
scene.add(ground);
// Obstacles
createObstacles();
// Spider
spider = createSpider();
scene.add(spider);
// Listeners
window.addEventListener("resize", onWindowResize, false);
window.addEventListener("keydown", (e) => {
keyboard[e.code] = true;
});
window.addEventListener("keyup", (e) => {
keyboard[e.code] = false;
});
}
// Create a deformed ground plane using a sine/cosine height function.
function createGround() {
const size = 200;
const divisions = 128;
const geometry = new THREE.PlaneGeometry(size, size, divisions, divisions);
geometry.rotateX(-Math.PI / 2);
// Displace vertices using a height function.
const position = geometry.attributes.position;
for (let i = 0; i < position.count; i++) {
let x = position.getX(i);
let z = position.getZ(i);
const y = getGroundHeight(x, z);
position.setY(i, y);
}
geometry.computeVertexNormals();
const material = new THREE.MeshLambertMaterial({ color: 0x556b2f });
const mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
return mesh;
}
// Height function for ground based on sine/cosine functions.
function getGroundHeight(x, z) {
return Math.sin(x / 10) * 2 + Math.cos(z / 10) * 2;
}
// Create some obstacles (boxes and spheres) randomly placed.
function createObstacles() {
const obsMaterial = new THREE.MeshLambertMaterial({ color: 0x8b0000 });
for (let i = 0; i < 8; i++) {
// Randomly decide sphere or box
let mesh;
if (Math.random() > 0.5) {
const geo = new THREE.BoxGeometry(2, 2, 2);
mesh = new THREE.Mesh(geo, obsMaterial);
} else {
const geo = new THREE.SphereGeometry(1.5, 16, 16);
mesh = new THREE.Mesh(geo, obsMaterial);
}
const x = (Math.random() - 0.5) * 100;
const z = (Math.random() - 0.5) * 100;
const y = getGroundHeight(x, z) + 1; // raise a bit so it sits on the ground
mesh.position.set(x, y, z);
scene.add(mesh);
}
}
// Create the spider: a body and 8 procedurally animated legs using THREE.IK.
function createSpider() {
const spiderGroup = new THREE.Group();
// Spider body (an ellipsoid)
const bodyGeo = new THREE.SphereGeometry(2.5, 16, 16);
const bodyMat = new THREE.MeshLambertMaterial({ color: 0x222222 });
const bodyMesh = new THREE.Mesh(bodyGeo, bodyMat);
bodyMesh.scale.set(1.5, 0.7, 1);
spiderGroup.add(bodyMesh);
// Leg parameters
const legCount = 8;
const legSpreadAngle = Math.PI / 3; // how far legs are spread
const legLength = 4; // total length of each leg
const segmentsPerLeg = 3; // number of segments in each leg
// Arrange legs evenly around the body. Two on each quadrant.
for (let i = 0; i < legCount; i++) {
// Angle around the body for leg attachment:
const angle = (i / legCount) * Math.PI * 2;
// Calculate the attachment point on the body’s edge
const attachRadius = 2.5; // roughly
const attachX = Math.cos(angle) * attachRadius;
const attachZ = Math.sin(angle) * attachRadius;
const attachY = -0.5; // attach a little below the center
// For visualizing the leg base, you can add a small helper sphere (optional)
/*
const sphereGeo = new THREE.SphereGeometry(0.2, 8, 8);
const sphereMat = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const helper = new THREE.Mesh(sphereGeo, sphereMat);
helper.position.set(attachX, attachY, attachZ);
spiderGroup.add(helper);
*/
// Create a leg IK chain.
const legGroup = new THREE.Group();
legGroup.position.set(attachX, attachY, attachZ);
// Rotate the legGroup so that its “forward” is away from the body.
legGroup.rotation.y = angle + Math.PI / 2;
// Build IK chain for the leg:
const ik = new THREE.IK();
const chain = new THREE.IKChain();
// Create bones for the leg.
const bones = [];
let prevBone;
for (let j = 0; j < segmentsPerLeg; j++) {
const bone = new THREE.Bone();
if (j === 0) {
// First bone originates at legGroup origin.
bone.position.y = 0;
legGroup.add(bone);
} else {
// Each subsequent bone is attached to the previous bone.
bone.position.y = -legLength / segmentsPerLeg;
prevBone.add(bone);
}
bones.push(bone);
prevBone = bone;
}
// Build the IK joints.
// The first joint (hip) does not have a target; the last bone is the effector.
chain.add(new THREE.IKJoint(bones[0], { constraints: [] }));
chain.add(new THREE.IKJoint(bones[1], { constraints: [] }));
chain.add(new THREE.IKJoint(bones[2], { constraints: [] }));
ik.addChain(chain);
// Set the current target (effector) position to the end of the leg.
// We will update this target each frame so that the foot "finds" the ground.
ik.getTargetIKChain(0).setPosition(new THREE.Vector3(0, -legLength, 0));
legGroup.add(ik.getTargetIKChain(0)); // add target as child for visualization
// Optionally add a small sphere at the effector (foot) for visual debugging
const footGeo = new THREE.SphereGeometry(0.15, 8, 8);
const footMat = new THREE.MeshBasicMaterial({ color: 0xffff00 });
const footHelper = new THREE.Mesh(footGeo, footMat);
ik.getTargetIKChain(0).add(footHelper);
// Add IK bones for rendering (a simple visual representation)
// For simplicity we draw a line geometry representing the bones.
const boneMaterial = new THREE.LineBasicMaterial({ color: 0xffffff });
const bonePoints = [];
let currentPos = new THREE.Vector3();
bones[0].getWorldPosition(currentPos);
bonePoints.push(currentPos.clone());
for (let j = 0; j < bones.length; j++) {
bones[j].getWorldPosition(currentPos);
bonePoints.push(currentPos.clone());
}
const boneGeo = new THREE.BufferGeometry().setFromPoints(bonePoints);
const boneLine = new THREE.Line(boneGeo, boneMaterial);
// Note: This line will not update automatically; for a full debug render,
// you would need to update the vertices each frame. This sample focuses on IK.
// For now, we add the legGroup only.
// legGroup.add(boneLine);
// Save the leg system parameters.
legSystems.push({
ik: ik,
legGroup: legGroup,
// Store the initial local effector position relative to the leg base:
defaultEffectorPos: new THREE.Vector3(0, -legLength, 0).clone(),
currentTarget: new THREE.Vector3(0, -legLength, 0),
stepThreshold: 0.8,
});
// Add the leg group as a child of the spider body.
spiderGroup.add(legGroup);
// Also add the IK bones and target to the spiderGroup
spiderGroup.add(ik.getRootBone(0)); // add the chain (the root bone is already in legGroup, but ensure hierarchy)
}
return spiderGroup;
}
// Update the procedural leg IK targets.
function updateLegIK() {
// For each leg system, compute an ideal target based on the spider’s current world position.
legSystems.forEach((leg) => {
// Determine the foot’s desired world position:
// Start with the leg group’s world position, then extend downward by the leg length.
const legWorldPos = new THREE.Vector3();
leg.legGroup.getWorldPosition(legWorldPos);
// For a simple “stepping” effect, we can add a slight forward offset if moving.
let moveOffset = new THREE.Vector3();
if (keyboard["KeyW"] || keyboard["ArrowUp"]) moveOffset.z -= 1;
if (keyboard["KeyS"] || keyboard["ArrowDown"]) moveOffset.z += 1;
if (keyboard["KeyA"] || keyboard["ArrowLeft"]) moveOffset.x -= 1;
if (keyboard["KeyD"] || keyboard["ArrowRight"]) moveOffset.x += 1;
moveOffset.normalize().multiplyScalar(0.8);
// Ideal target in world space.
let idealTarget = legWorldPos.clone();
idealTarget.add(new THREE.Vector3(moveOffset.x, 0, moveOffset.z));
// Lower the ideal target by the full leg length.
idealTarget.y -= 4;
// Now adjust the y-value based on the ground height at that x,z.
idealTarget.y = getGroundHeight(idealTarget.x, idealTarget.z) + 0.1; // a slight offset above ground
// Smoothly update current target toward ideal target if far away.
if (leg.currentTarget.distanceTo(idealTarget) > leg.stepThreshold) {
leg.currentTarget.lerp(idealTarget, 0.2);
}
// Update the IK target position in the leg’s IK system.
leg.ik.getTargetIKChain(0).position.copy(leg.currentTarget);
// Solve the IK chain.
leg.ik.solve();
});
}
// Update the spider’s position based on keyboard controls.
function updateSpiderMovement() {
const direction = new THREE.Vector3();
if (keyboard["KeyW"] || keyboard["ArrowUp"]) direction.z -= 1;
if (keyboard["KeyS"] || keyboard["ArrowDown"]) direction.z += 1;
if (keyboard["KeyA"] || keyboard["ArrowLeft"]) direction.x -= 1;
if (keyboard["KeyD"] || keyboard["ArrowRight"]) direction.x += 1;
if (direction.length() > 0) {
direction.normalize();
// Move in the local forward direction.
spider.position.add(direction.multiplyScalar(spiderSpeed));
// Rotate the spider to face the movement direction (simple approximation).
const targetAngle = Math.atan2(direction.x, direction.z);
spider.rotation.y = targetAngle;
}
}
// Animation loop
function animate() {
requestAnimationFrame(animate);
updateSpiderMovement();
updateLegIK();
controls.update();
renderer.render(scene, camera);
}
// Handle window resize
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
</script>
</body>
</html>
How It Works
Scene Setup:
A basic scene is created with a perspective camera, ambient and directional lighting, and OrbitControls to allow the user to look around.
Ground & Obstacles:
The ground is created from a large plane geometry whose vertex heights are displaced via the function getGroundHeight(x,z). Several box/sphere obstacles are randomly scattered on the terrain.
Spider Construction:
The spider is built as a group with a body mesh and eight legs. Each leg is attached at a different angle around the body. Each leg is represented as an IK chain (using THREE.IK) with three joints. A target (the “foot”) is added to each chain which is adjusted each frame.
IK Animation:
In the update loop, each leg computes its “ideal” foot placement (based on its attachment point and a forward offset when moving) and blends the IK target toward that ideal position if it’s too far away. The IK solver then adjusts the joint angles.
Spider Movement:
The WASD keys (or arrow keys) move the spider’s body. As the spider moves, the IK targets update so the legs seem to “reach” for the ground.
Unified HTML File:
All code (HTML, CSS, and JavaScript) is included in a single file. Just open the file in your browser to see the demo.
Feel free to further refine the IK constraints, stepping gait, leg visuals, and improve ground complexity as needed. Enjoy experimenting with procedural animation using Three.js and THREE.IK!