Of course. Here is a complete, self-contained HTML file that fulfills all the project requirements. It uses Three.js, THREE.IK, and procedurally animates a spider that adapts to uneven terrain, controlled by the user.
Key Features Implemented:
- Procedural Animation: The spider's legs don't follow a pre-baked animation. They react to the spider's body movement and the ground height.
- Inverse Kinematics (IK):
THREE.IK is used to calculate the joint angles for each leg so that the "foot" (end effector) reaches its target position on the ground.
- Gait Cycle: A simple but effective gait cycle is implemented. The spider alternates which set of legs it moves, ensuring stability and a more realistic crawling motion. A leg decides to step when it gets too far from its "home" position relative to the moving body.
- Terrain Adaptation: A
Raycaster is used to find the exact ground height for each footstep, allowing the spider to walk up and down hills naturally.
- User Controls:
- W/A/S/D: Move the spider forward/left/backward/right.
- Mouse: Orbit the camera to view the action from any angle.
- Dynamic Environment: The ground is a procedurally generated
PlaneGeometry with hills and valleys, and a few simple obstacles are scattered on it.
- Single File Output: All HTML, CSS, and JavaScript are contained within one file as requested.
How to Use:
- Save the code below as an
.html file (e.g., spider_ik.html).
- Open the file in a modern web browser that supports ES6 modules (like Chrome, Firefox, or Edge).
- Use the W, A, S, D keys to move the spider and the mouse to rotate the camera.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Procedural Spider Animation with THREE.IK</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body { margin: 0; background-color: #333; color: #fff; font-family: monospace; }
canvas { display: block; }
#info {
position: absolute;
top: 10px;
width: 100%;
text-align: center;
z-index: 100;
display:block;
text-shadow: 1px 1px 2px #000;
}
</style>
</head>
<body>
<div id="info">
Procedural Spider Animation with THREE.IK<br/>
<b>Controls:</b> [W, A, S, D] to Move | [Mouse] to Orbit Camera
</div>
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/es-module-shims@1.3.6/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.148.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.148.0/examples/jsm/",
"three-ik": "https://cdn.jsdelivr.net/npm/three-ik@0.1.0/build/three-ik.min.js"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { IK, IKChain, IKJoint, IKHelper } from 'three-ik';
// --- GLOBAL VARS & CONSTANTS ---
let scene, camera, renderer, controls, clock;
let ground, spider, ik;
const keys = { w: false, a: false, s: false, d: false };
const raycaster = new THREE.Raycaster();
// Spider animation parameters
const spiderState = {
speed: 0,
velocity: new THREE.Vector3(),
turnSpeed: 0,
moveSpeed: 2.5,
turnRate: Math.PI / 2,
};
const legStates = [];
const gait = [
[0, 3, 4, 7], // Gait group 1
[1, 2, 5, 6] // Gait group 2
];
let currentGait = 0;
const STEP_DISTANCE = 0.8;
const STEP_HEIGHT = 0.5;
const STEP_SPEED = 5.0;
// --- INITIALIZATION ---
init();
animate();
function init() {
// Basic setup
clock = new THREE.Clock();
scene = new THREE.Scene();
scene.background = new THREE.Color(0x87ceeb);
scene.fog = new THREE.Fog(0x87ceeb, 20, 100);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
document.body.appendChild(renderer.domElement);
// Camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(5, 5, 5);
// Controls
controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 1, 0);
controls.update();
// Lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
directionalLight.position.set(10, 20, 5);
directionalLight.castShadow = true;
directionalLight.shadow.camera.top = 15;
directionalLight.shadow.camera.bottom = -15;
directionalLight.shadow.camera.left = -15;
directionalLight.shadow.camera.right = 15;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
scene.add(directionalLight);
// Environment
createGround();
createObstacles();
// Spider
spider = createSpider();
scene.add(spider);
setupIK();
// Event Listeners
window.addEventListener('resize', onWindowResize);
document.addEventListener('keydown', (e) => (keys[e.key.toLowerCase()] = true));
document.addEventListener('keyup', (e) => (keys[e.key.toLowerCase()] = false));
}
// --- WORLD CREATION ---
function createGround() {
const geometry = new THREE.PlaneGeometry(100, 100, 100, 100);
const material = new THREE.MeshStandardMaterial({
color: 0x4a6b25,
roughness: 0.9,
metalness: 0.1,
});
ground = new THREE.Mesh(geometry, material);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
// Deform vertices to create hills/valleys
const vertices = geometry.attributes.position.array;
for (let i = 2; i < vertices.length; i += 3) {
const x = vertices[i - 2];
const y = vertices[i - 1];
vertices[i] = (Math.sin(x * 0.2) * Math.cos(y * 0.2)) * 2;
}
geometry.attributes.position.needsUpdate = true;
geometry.computeVertexNormals();
scene.add(ground);
}
function createObstacles() {
const obstacles = [];
const boxGeo = new THREE.BoxGeometry(2, 2, 2);
const sphereGeo = new THREE.SphereGeometry(1.2, 16, 16);
const mat = new THREE.MeshStandardMaterial({ color: 0x888888, roughness: 0.8 });
const positions = [
new THREE.Vector3(5, 0, -5),
new THREE.Vector3(-8, 0, 7),
new THREE.Vector3(10, 0, 10)
];
positions.forEach((pos, i) => {
const geo = i % 2 === 0 ? boxGeo : sphereGeo;
const obstacle = new THREE.Mesh(geo, mat);
obstacle.castShadow = true;
obstacle.receiveShadow = true;
// Raycast to place on ground
raycaster.set(new THREE.Vector3(pos.x, 20, pos.z), new THREE.Vector3(0, -1, 0));
const intersects = raycaster.intersectObject(ground);
if(intersects.length > 0) {
obstacle.position.copy(intersects[0].point);
obstacle.position.y += (i % 2 === 0 ? 1 : 1.2); // Adjust for half-height
}
scene.add(obstacle);
obstacles.push(obstacle);
});
}
// --- SPIDER & IK CREATION ---
function createSpider() {
const spiderGroup = new THREE.Group();
// Body
const bodyMaterial = new THREE.MeshStandardMaterial({ color: 0x221100, roughness: 0.4 });
const bodyGeometry = new THREE.CapsuleGeometry(0.4, 0.5, 4, 8);
const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
body.castShadow = true;
body.name = "body";
spiderGroup.add(body);
spiderGroup.position.y = 3; // Start a bit high
// Legs
const legMaterial = new THREE.MeshStandardMaterial({ color: 0x332211, roughness: 0.7 });
const segmentGeom = new THREE.BoxGeometry(0.1, 0.1, 0.5);
segmentGeom.translate(0, 0, 0.25); // Pivot at the end
const legPositions = [
{ angle: Math.PI / 4, side: 1 }, { angle: -Math.PI / 4, side: -1 },
{ angle: Math.PI / 2, side: 1 }, { angle: -Math.PI / 2, side: -1 },
{ angle: 3 * Math.PI / 4, side: 1 }, { angle: -3 * Math.PI / 4, side: -1 },
{ angle: Math.PI, side: 1 }, { angle: -Math.PI, side: -1 }
];
for (let i = 0; i < 8; i++) {
const chain = new THREE.Object3D();
chain.name = `leg_${i}`;
const bone1 = new THREE.Bone();
const bone2 = new THREE.Bone();
const bone3 = new THREE.Bone();
bone1.add(bone2);
bone2.add(bone3);
chain.add(bone1);
// Attach visual meshes to bones
const mesh1 = new THREE.Mesh(segmentGeom, legMaterial);
mesh1.scale.set(1.5, 1.5, 1);
mesh1.castShadow = true;
bone1.add(mesh1);
const mesh2 = new THREE.Mesh(segmentGeom, legMaterial);
mesh2.scale.set(1.2, 1.2, 1.8);
mesh2.castShadow = true;
bone2.add(mesh2);
bone2.position.z = 0.5;
const mesh3 = new THREE.Mesh(segmentGeom, legMaterial);
mesh3.scale.set(1, 1, 2.2);
mesh3.castShadow = true;
bone3.add(mesh3);
bone3.position.z = 0.5 * 1.8;
// Position and orient the leg base
const pos = legPositions[i];
bone1.rotation.y = pos.angle;
bone1.rotation.z = pos.side * Math.PI / 4;
body.add(chain);
// Create IK target helper and initial state
const target = new THREE.Object3D();
target.name = `target_${i}`;
// const targetHelper = new THREE.AxesHelper(0.5);
// target.add(targetHelper);
scene.add(target);
legStates.push({
target: target,
isMoving: false,
stepStart: new THREE.Vector3(),
stepEnd: new THREE.Vector3(),
stepProgress: 0,
homePosition: new THREE.Vector3()
});
}
return spiderGroup;
}
function setupIK() {
ik = new IK();
const body = spider.getObjectByName('body');
for (let i = 0; i < 8; i++) {
const chain = new IKChain();
const leg = body.getObjectByName(`leg_${i}`);
const bones = [];
leg.traverse(obj => {
if (obj.isBone) bones.push(obj);
});
for (let j = 0; j < bones.length; j++) {
const joint = new IKJoint(bones[j], {
// Constraints to make movement more natural
constraints: j === 0 ? [] : [new THREE.Vector3(1, 0, 0)]
});
chain.add(joint, { target: j === bones.length - 1 ? legStates[i].target : null });
}
ik.add(chain);
}
}
// --- ANIMATION LOOP ---
function animate() {
requestAnimationFrame(animate);
const delta = clock.getDelta();
updateSpiderMovement(delta);
updateLegs(delta);
if (ik) ik.update();
controls.update();
renderer.render(scene, camera);
}
function updateSpiderMovement(delta) {
// Turning
let turnDirection = 0;
if (keys.a) turnDirection = 1;
if (keys.d) turnDirection = -1;
spiderState.turnSpeed = turnDirection * spiderState.turnRate;
spider.rotation.y += spiderState.turnSpeed * delta;
// Forward/Backward Movement
let moveDirection = 0;
if (keys.w) moveDirection = 1;
if (keys.s) moveDirection = -1;
spiderState.speed = moveDirection * spiderState.moveSpeed;
// Calculate velocity vector based on spider's rotation
const forward = new THREE.Vector3(0, 0, 1).applyQuaternion(spider.quaternion);
spiderState.velocity.copy(forward).multiplyScalar(spiderState.speed * delta);
spider.position.add(spiderState.velocity);
// Adjust body height to ground
raycaster.set(spider.position, new THREE.Vector3(0, -1, 0));
const intersects = raycaster.intersectObject(ground);
if (intersects.length > 0) {
const targetY = intersects[0].point.y + 0.8; // Desired height above ground
spider.position.y += (targetY - spider.position.y) * 0.1; // Smooth transition
}
}
function updateLegs(delta) {
let canMove = true;
const movingLegsInGait = gait[currentGait].filter(legIndex => legStates[legIndex].isMoving);
if (movingLegsInGait.length > 0) {
canMove = false; // Wait for current gait group to finish
}
// Determine home position for each leg foot
for (let i = 0; i < legStates.length; i++) {
const state = legStates[i];
const legBone = spider.getObjectByName(`leg_${i}`).children[0];
const homeOffset = new THREE.Vector3( (i % 2 === 0 ? 1.5 : -1.5), -0.8, (Math.floor(i/2) - 1.5) * 0.8 );
state.homePosition.copy(homeOffset).applyQuaternion(spider.quaternion).add(spider.position);
}
// Switch gait group if the other is done
const otherGait = (currentGait + 1) % 2;
const movingLegsInOtherGait = gait[otherGait].filter(legIndex => legStates[legIndex].isMoving);
if (movingLegsInOtherGait.length === 0) {
currentGait = otherGait;
}
for (let i = 0; i < legStates.length; i++) {
const state = legStates[i];
if (state.isMoving) {
// Animate the step
state.stepProgress += delta * STEP_SPEED;
if (state.stepProgress >= 1) {
state.stepProgress = 1;
state.isMoving = false;
state.target.position.copy(state.stepEnd);
} else {
// Lerp position
state.target.position.lerpVectors(state.stepStart, state.stepEnd, state.stepProgress);
// Add arc to the step
state.target.position.y += Math.sin(state.stepProgress * Math.PI) * STEP_HEIGHT;
}
} else {
// Check if a step is needed
const distance = state.target.position.distanceTo(state.homePosition);
if (distance > STEP_DISTANCE && gait[currentGait].includes(i) && canMove) {
state.isMoving = true;
state.stepProgress = 0;
state.stepStart.copy(state.target.position);
// Find a valid landing spot for the step end
raycaster.set(new THREE.Vector3(state.homePosition.x, state.homePosition.y + 2, state.homePosition.z), new THREE.Vector3(0, -1, 0));
const intersects = raycaster.intersectObject(ground);
if (intersects.length > 0) {
state.stepEnd.copy(intersects[0].point);
} else {
state.stepEnd.copy(state.homePosition); // Fallback
}
canMove = false; // Only one leg starts moving per frame
}
}
}
}
// --- EVENT HANDLERS ---
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
</script>
</body>
</html>