Here's a single .html file containing the interactive 3D spider animation using Three.js.
This solution implements:
- A procedurally generated terrain with hills and valleys.
- Randomly scattered obstacles (spheres and boxes).
- A spider model with a body and eight multi-jointed legs.
- A procedural walking animation system where:
- Legs adapt to the ground using a combination of Inverse Kinematics (FABRIK algorithm) and raycasting.
- The spider automatically finds suitable foot placement targets on the uneven terrain.
- A simple alternating gait (left vs. right leg groups) is used.
- Keyboard controls (W, A, S, D) for moving the spider.
- Mouse-controlled orbital camera to view the scene from any angle.
<!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; font-family: sans-serif; }
canvas { display: block; }
#info {
position: absolute;
top: 10px;
left: 10px;
color: white;
background: rgba(0, 0, 0, 0.5);
padding: 10px;
border-radius: 5px;
font-size: 14px;
}
</style>
</head>
<body>
<div id="info">
<h3>Spider Controls:</h3>
<ul>
<li><b>W</b>: Move Forward</li>
<li><b>A</b>: Move Left</li>
<li><b>S</b>: Move Backward</li>
<li><b>D</b>: Move Right</li>
</ul>
<h3>Camera Controls:</h3>
<ul>
<li><b>Left Click + Drag</b>: Orbit Camera</li>
<li><b>Scroll Wheel</b>: Zoom In/Out</li>
</ul>
</div>
<script type="module">
import * as THREE from 'https://cdn.jsdelivr.net/npm/three@0.155.0/build/three.module.js';
import { OrbitControls } from 'https://cdn.jsdelivr.net/npm/three@0.155.0/examples/jsm/controls/OrbitControls.js';
// --- Core Setup ---
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
renderer.setClearColor(0x87CEEB); // Sky blue background
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
// --- Lights ---
const ambientLight = new THREE.AmbientLight(0x404040, 2); // Soft white light
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(50, 100, 50);
directionalLight.castShadow = true;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
directionalLight.shadow.camera.near = 0.5;
directionalLight.shadow.camera.far = 200;
directionalLight.shadow.camera.left = -100;
directionalLight.shadow.camera.right = 100;
directionalLight.shadow.camera.top = 100;
directionalLight.shadow.camera.bottom = -100;
scene.add(directionalLight);
// --- OrbitControls ---
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true; // Smooth camera movement
controls.dampingFactor = 0.05;
controls.minDistance = 5;
controls.maxDistance = 50;
camera.position.set(10, 10, 10);
controls.update();
// --- Ground Plane (Terrain) ---
const terrainWidth = 100;
const terrainDepth = 100;
const segments = 100; // More segments for more detail
const terrainGeometry = new THREE.PlaneGeometry(terrainWidth, terrainDepth, segments, segments);
terrainGeometry.rotateX(-Math.PI / 2); // Rotate to be flat on XZ plane
const positionAttribute = terrainGeometry.attributes.position;
const vertex = new THREE.Vector3();
const noiseScale = 5; // How spread out the hills are
const heightScale = 3; // How tall the hills are
// Simple pseudo-random noise for terrain generation
function getNoise(x, z) {
return Math.sin(x * 0.5 / noiseScale) * Math.cos(z * 0.5 / noiseScale) * heightScale +
Math.sin(x * 1.2 / noiseScale) * Math.cos(z * 1.2 / noiseScale) * heightScale * 0.5;
}
for (let i = 0; i < positionAttribute.count; i++) {
vertex.fromBufferAttribute(positionAttribute, i);
vertex.y = getNoise(vertex.x, vertex.z);
positionAttribute.setY(i, vertex.y);
}
terrainGeometry.computeVertexNormals(); // Crucial for proper lighting
const terrainMaterial = new THREE.MeshPhongMaterial({ color: 0x228B22, side: THREE.DoubleSide }); // Forest Green
const terrain = new THREE.Mesh(terrainGeometry, terrainMaterial);
terrain.receiveShadow = true;
scene.add(terrain);
// --- Obstacles ---
const obstacleMaterial = new THREE.MeshPhongMaterial({ color: 0x8B4513 }); // Brown
const numObstacles = 10;
const obstacles = [];
for (let i = 0; i < numObstacles; i++) {
const isSphere = Math.random() > 0.5;
let obstacleGeometry;
let size;
if (isSphere) {
size = Math.random() * 1.5 + 0.5; // Radius between 0.5 and 2
obstacleGeometry = new THREE.SphereGeometry(size, 16, 16);
} else {
size = Math.random() * 1.5 + 0.5; // Side length between 0.5 and 2
obstacleGeometry = new THREE.BoxGeometry(size, size, size);
}
const obstacle = new THREE.Mesh(obstacleGeometry, obstacleMaterial);
obstacle.castShadow = true;
obstacle.receiveShadow = true;
// Random position within terrain bounds
let ox = (Math.random() - 0.5) * terrainWidth * 0.8;
let oz = (Math.random() - 0.5) * terrainDepth * 0.8;
let oy = getNoise(ox, oz) + size / 2; // Place on top of terrain
obstacle.position.set(ox, oy, oz);
scene.add(obstacle);
obstacles.push(obstacle);
}
// --- Spider Class ---
class Spider {
constructor(scene, ground, obstacles) {
this.scene = scene;
this.ground = ground; // The terrain mesh
this.raycaster = new THREE.Raycaster();
this.groundObjects = [this.ground, ...obstacles];
this.body = new THREE.Mesh(
new THREE.SphereGeometry(1.5, 16, 16),
new THREE.MeshPhongMaterial({ color: 0x333333 })
);
this.body.castShadow = true;
this.body.receiveShadow = true;
this.body.position.y = 2; // Initial position above ground
this.scene.add(this.body);
controls.target.copy(this.body.position); // Make camera follow spider
this.legs = [];
this.numLegs = 8;
// Leg segment lengths
this.coxaLength = 0.5;
this.femurLength = 1.2;
this.tibiaLength = 1.3;
// IK tolerance and iterations for FABRIK
this.ikTolerance = 0.05;
this.ikMaxIterations = 10;
// Gait parameters
this.stepHeight = 1.5; // How high a leg lifts during a step
this.stepSpeed = 0.5; // How fast a leg moves (duration in seconds)
this.stepDistance = 3; // How far a leg steps forward from its base
// Leg states: IDLE, LIFTING, SWINGING, PLANTING
this.legStates = [];
this.legTimers = []; // For smooth transitions
this.legCurrentTargets = []; // Current world position of the foot
this.legDesiredTargets = []; // Where the foot should move next
// Leg groups for alternating gait (even/odd indexed legs)
this.activeGroup = 0; // 0 for even-indexed legs, 1 for odd-indexed legs
this.initLegs();
this.initLegTargets(); // Initialize leg current targets to ground positions
// Movement control
this.velocity = new THREE.Vector3();
this.moveDirection = new THREE.Vector3(); // Current desired movement direction from input
this.speed = 5; // Spider's movement speed (units per second)
}
// Initializes the spider's leg geometry and attaches them to the body
initLegs() {
const legCount = this.numLegs;
const angleIncrement = (Math.PI * 2) / legCount;
for (let i = 0; i < legCount; i++) {
const angle = angleIncrement * i; // Angle around body for leg base position
// Proximal segment (coxa)
const coxa = new THREE.Mesh(
new THREE.CylinderGeometry(0.15, 0.15, this.coxaLength, 8),
new THREE.MeshPhongMaterial({ color: 0x666666 })
);
coxa.castShadow = true;
coxa.receiveShadow = true;
coxa.geometry.translate(0, this.coxaLength / 2, 0); // Pivot at bottom, extends along +Y
// Femur
const femur = new THREE.Mesh(
new THREE.CylinderGeometry(0.12, 0.12, this.femurLength, 8),
new THREE.MeshPhongMaterial({ color: 0x666666 })
);
femur.castShadow = true;
femur.receiveShadow = true;
femur.geometry.translate(0, this.femurLength / 2, 0);
femur.position.y = this.coxaLength; // Attach to end of coxa along Y
coxa.add(femur);
// Tibia (distal segment)
const tibia = new THREE.Mesh(
new THREE.CylinderGeometry(0.1, 0.1, this.tibiaLength, 8),
new THREE.MeshPhongMaterial({ color: 0x666666 })
);
tibia.castShadow = true;
tibia.receiveShadow = true;
tibia.geometry.translate(0, this.tibiaLength / 2, 0);
tibia.position.y = this.femurLength; // Attach to end of femur along Y
femur.add(tibia);
// Position coxa relative to body
const legOutwardOffset = 1.0; // Distance from body center
const x_offset = Math.cos(angle) * legOutwardOffset;
const z_offset = Math.sin(angle) * legOutwardOffset;
coxa.position.set(x_offset, 0, z_offset); // Base of coxa relative to body center
// Initial rotation of coxa to point outwards and slightly downwards
// coxa.rotation.y: Yaw (horizontal swivel)
// coxa.rotation.x: Pitch (up/down swing)
coxa.rotation.y = angle + Math.PI / 2; // Point outwards in XZ plane relative to body
coxa.rotation.x = -Math.PI / 3; // Angle downwards (~60 degrees from vertical)
this.body.add(coxa);
this.legs.push({
coxa: coxa,
femur: femur,
tibia: tibia,
id: i
});
this.legStates[i] = 'IDLE';
this.legTimers[i] = 0;
this.legCurrentTargets[i] = new THREE.Vector3();
this.legDesiredTargets[i] = new THREE.Vector3();
}
}
// Finds the ground intersection point for a given world position
getGroundIntersection(worldPosition) {
const origin = new THREE.Vector3(worldPosition.x, worldPosition.y + 10, worldPosition.z); // Start ray high
const direction = new THREE.Vector3(0, -1, 0); // Point downwards
this.raycaster.set(origin, direction);
const intersects = this.raycaster.intersectObjects(this.groundObjects, true);
if (intersects.length > 0) {
// Find the closest intersection that is not part of the spider itself
for (const intersect of intersects) {
let isSpiderPart = false;
let obj = intersect.object;
while(obj) {
if (obj === this.body || (this.legs.some(l => l.coxa === obj || l.femur === obj || l.tibia === obj))) {
isSpiderPart = true;
break;
}
obj = obj.parent;
}
if (!isSpiderPart) {
return intersect.point;
}
}
}
return null; // No valid ground found
}
// Initializes leg targets by placing feet on the ground beneath their initial positions
initLegTargets() {
for (let i = 0; i < this.numLegs; i++) {
const leg = this.legs[i];
const coxaWorldPos = new THREE.Vector3();
leg.coxa.getWorldPosition(coxaWorldPos);
// Estimate initial foot position (straight down from coxa)
const tempFootPos = coxaWorldPos.clone();
// Max possible leg extension (approx)
tempFootPos.y -= (this.coxaLength + this.femurLength + this.tibiaLength) * 0.8;
const groundPoint = this.getGroundIntersection(tempFootPos);
if (groundPoint) {
this.legCurrentTargets[i].copy(groundPoint);
this.legDesiredTargets[i].copy(groundPoint); // Start desired at current
this.applyIK(leg, groundPoint);
} else {
// Fallback if no ground found
this.legCurrentTargets[i].copy(tempFootPos);
this.legDesiredTargets[i].copy(tempFootPos);
console.warn(`Leg ${i} could not find ground initially.`);
}
}
this.updateBodyHeight(); // Adjust body to average leg height
}
// Inverse Kinematics (FABRIK) to position leg joints
applyIK(leg, targetPos) {
const coxa = leg.coxa;
const femur = leg.femur;
const tibia = leg.tibia;
// Get current world positions of joints
// These are the pivots of the segments.
const p0_world = new THREE.Vector3().setFromMatrixPosition(coxa.matrixWorld); // Coxa origin
const p1_world = new THREE.Vector3().setFromMatrixPosition(femur.matrixWorld); // Femur origin (end of coxa)
const p2_world = new THREE.Vector3().setFromMatrixPosition(tibia.matrixWorld); // Tibia origin (end of femur)
// Calculate current foot position (end of tibia)
const currentFootPos = new THREE.Vector3();
tibia.getWorldPosition(currentFootPos);
// Tibia is Y-up, so its length is along its local Y axis
const tibiaEndOffset = new THREE.Vector3(0, this.tibiaLength, 0);
// Transform offset into world space based on tibia's current orientation
tibiaEndOffset.applyQuaternion(tibia.quaternion);
currentFootPos.add(tibiaEndOffset);
const points = [p0_world, p1_world, p2_world, currentFootPos];
const lengths = [this.coxaLength, this.femurLength, this.tibiaLength];
const root = points[0].clone(); // Fixed point for the chain
const target = targetPos.clone(); // The desired end-effector position
// Clamp target if unreachable
const totalLength = lengths[0] + lengths[1] + lengths[2];
const distToTargetFromRoot = root.distanceTo(target);
if (distToTargetFromRoot > totalLength) {
const dir = target.clone().sub(root).normalize();
target.copy(root).add(dir.multiplyScalar(totalLength - this.ikTolerance));
}
// FABRIK iteration
let currentDist = points[3].distanceTo(target);
let iteration = 0;
while (currentDist > this.ikTolerance && iteration < this.ikMaxIterations) {
// Backward pass (from target to root)
points[3].copy(target);
for (let i = points.length - 2; i >= 0; i--) {
const segmentLength = lengths[i];
const dir = points[i].clone().sub(points[i+1]).normalize();
points[i].copy(points[i+1]).add(dir.multiplyScalar(segmentLength));
}
// Forward pass (from root to target)
points[0].copy(root); // Anchor the root
for (let i = 0; i < points.length - 1; i++) {
const segmentLength = lengths[i];
const dir = points[i+1].clone().sub(points[i]).normalize();
points[i+1].copy(points[i]).add(dir.multiplyScalar(segmentLength));
}
currentDist = points[3].distanceTo(target);
iteration++;
}
// Apply rotations to each joint based on new positions
// Legs are Y-up cylinders.
// Coxa rotation (world space to local of parent, then apply)
const desiredCoxaDir = points[1].clone().sub(points[0]).normalize();
const currentCoxaDirInWorld = new THREE.Vector3(0, 1, 0).applyQuaternion(coxa.quaternion.clone());
const qCoxa = new THREE.Quaternion().setFromUnitVectors(currentCoxaDirInWorld, desiredCoxaDir);
coxa.quaternion.premultiply(qCoxa);
// Femur rotation
const desiredFemurDir = points[2].clone().sub(points[1]).normalize();
const currentFemurDirInWorld = new THREE.Vector3(0, 1, 0).applyQuaternion(femur.quaternion.clone());
const qFemur = new THREE.Quaternion().setFromUnitVectors(currentFemurDirInWorld, desiredFemurDir);
femur.quaternion.premultiply(qFemur);
// Tibia rotation
const desiredTibiaDir = points[3].clone().sub(points[2]).normalize();
const currentTibiaDirInWorld = new THREE.Vector3(0, 1, 0).applyQuaternion(tibia.quaternion.clone());
const qTibia = new THREE.Quaternion().setFromUnitVectors(currentTibiaDirInWorld, desiredTibiaDir);
tibia.quaternion.premultiply(qTibia);
}
// Adjusts the spider's body height based on the average height of its grounded legs
updateBodyHeight() {
let avgY = 0;
let groundedLegsCount = 0;
for (let i = 0; i < this.numLegs; i++) {
// Only consider legs that are currently on the ground or about to land
if (this.legStates[i] === 'IDLE' || this.legStates[i] === 'PLANTING') {
avgY += this.legCurrentTargets[i].y;
groundedLegsCount++;
}
}
if (groundedLegsCount > 0) {
avgY /= groundedLegsCount;
} else {
// Fallback to raycast if no legs are grounded (e.g., in mid-air for some reason)
const origin = this.body.position.clone();
origin.y += 10;
this.raycaster.set(origin, new THREE.Vector3(0, -1, 0));
const intersects = this.raycaster.intersectObjects(this.groundObjects, true);
if (intersects.length > 0) {
avgY = intersects[0].point.y;
} else {
avgY = 0; // Default if no ground at all
}
}
// Desired hover height above the average ground
const desiredBodyY = avgY + (this.coxaLength + this.femurLength + this.tibiaLength) * 0.4;
this.body.position.y = THREE.MathUtils.lerp(this.body.position.y, desiredBodyY, 0.1); // Smooth transition
}
// Main update loop for the spider's animation and movement
update(deltaTime) {
// Update spider's world rotation based on moveDirection (from keyboard input)
if (this.moveDirection.lengthSq() > 0.01) { // If there's a significant movement direction
// Calculate target angle based on global Z-axis (forward) and movement vector
const targetAngle = Math.atan2(this.moveDirection.x, this.moveDirection.z);
const currentAngle = new THREE.Euler().setFromQuaternion(this.body.quaternion, 'YXZ').y; // Get current yaw
let angleDiff = targetAngle - currentAngle;
// Normalize angle difference to be within -PI to PI
if (angleDiff > Math.PI) angleDiff -= 2 * Math.PI;
if (angleDiff < -Math.PI) angleDiff += 2 * Math.PI;
// Apply smooth rotation to the body
const rotationSpeed = 5; // Rotation speed multiplier
this.body.rotation.y += angleDiff * rotationSpeed * deltaTime;
}
// Move spider body in its local forward direction (its Z-axis) if velocity is set
const currentSpeed = this.velocity.length();
if (currentSpeed > 0.01) {
const forwardVector = new THREE.Vector3(0, 0, 1); // Local Z-axis is forward
forwardVector.applyQuaternion(this.body.quaternion); // Transform to world space
forwardVector.multiplyScalar(currentSpeed * deltaTime);
this.body.position.add(forwardVector);
}
// Keep camera target on the spider's body
controls.target.copy(this.body.position);
// --- Leg Animation and Gait ---
const isMoving = this.velocity.lengthSq() > 0.01;
for (let i = 0; i < this.numLegs; i++) {
const leg = this.legs[i];
const legState = this.legStates[i];
this.legTimers[i] += deltaTime;
const currentFootWorldPos = new THREE.Vector3();
leg.tibia.getWorldPosition(currentFootWorldPos); // Current actual foot position (end of tibia)
// Add the tibia length offset to get the very end of the leg (foot)
const tibiaLocalY = new THREE.Vector3(0, this.tibiaLength, 0);
tibiaLocalY.applyQuaternion(leg.tibia.quaternion);
currentFootWorldPos.add(tibiaLocalY);
// Determine max reach distance for a leg before it needs to step
const legMaxReach = (this.coxaLength + this.femurLength + this.tibiaLength) * 0.8; // Max comfortable extension
const legMinReach = (this.coxaLength + this.femurLength + this.tibiaLength) * 0.4; // Min comfortable extension (when bent)
const hipWorldPos = new THREE.Vector3();
leg.coxa.getWorldPosition(hipWorldPos);
const distanceFromHip = currentFootWorldPos.distanceTo(hipWorldPos);
// Determine if leg needs to step (too far, or its group is active and spider is moving)
const isLegGroupActive = (i % 2 === this.activeGroup);
const shouldStep = (isMoving && isLegGroupActive && distanceFromHip > legMaxReach * 0.8) || (distanceFromHip > legMaxReach);
switch (legState) {
case 'IDLE':
if (shouldStep) {
// Calculate new desired target point for the foot
const forwardDirection = this.body.getWorldDirection(new THREE.Vector3());
const currentFootOnGround = this.legCurrentTargets[i].clone();
// Target point is forward from current foot position
let newTargetCandidate = currentFootOnGround.clone().add(forwardDirection.multiplyScalar(this.stepDistance));
// Raycast to find actual ground height at the new target
const groundPoint = this.getGroundIntersection(newTargetCandidate);
if (groundPoint) {
this.legDesiredTargets[i].copy(groundPoint);
this.legStates[i] = 'LIFTING';
this.legTimers[i] = 0;
// Switch active group immediately after one leg starts stepping, for a ripple effect
this.activeGroup = (this.activeGroup + 1) % 2;
}
} else if (!isMoving && distanceFromHip > legMinReach) {
// If not moving, gently bring legs to a resting position
const restPosition = new THREE.Vector3();
leg.coxa.getWorldPosition(restPosition); // Base of coxa in world
restPosition.add(new THREE.Vector3(0, -(this.coxaLength + this.femurLength + this.tibiaLength) * 0.5, 0)); // Approx below hip
const groundPoint = this.getGroundIntersection(restPosition);
if (groundPoint && currentFootWorldPos.distanceTo(groundPoint) > 0.1) {
this.applyIK(leg, groundPoint);
this.legCurrentTargets[i].copy(groundPoint);
}
}
break;
case 'LIFTING':
const liftProgress = Math.min(1, this.legTimers[i] / (this.stepSpeed * 0.2)); // 20% of step time for lifting
const startPosLift = this.legCurrentTargets[i].clone();
const midPosLift = this.legDesiredTargets[i].clone(); // The mid-point of the swing path, at full lift height
const interpolatedLiftPos = new THREE.Vector3().lerpVectors(startPosLift, midPosLift, liftProgress);
interpolatedLiftPos.y = THREE.MathUtils.lerp(startPosLift.y, startPosLift.y + this.stepHeight, liftProgress); // Arc upwards
this.applyIK(leg, interpolatedLiftPos);
if (liftProgress >= 1) {
this.legStates[i] = 'SWINGING';
this.legTimers[i] = 0;
}
break;
case 'SWINGING':
const swingProgress = Math.min(1, this.legTimers[i] / (this.stepSpeed * 0.6)); // 60% of step time for swinging
const startPosSwing = this.legCurrentTargets[i].clone(); // Point where it started lift from
const endPosSwing = this.legDesiredTargets[i].clone(); // Final ground target
const interpolatedSwingX = THREE.MathUtils.lerp(startPosSwing.x, endPosSwing.x, swingProgress);
const interpolatedSwingZ = THREE.MathUtils.lerp(startPosSwing.z, endPosSwing.z, swingProgress);
// Arc Y motion during swing (up and then down)
const interpolatedSwingY = THREE.MathUtils.lerp(startPosSwing.y + this.stepHeight, endPosSwing.y, swingProgress) +
Math.sin(swingProgress * Math.PI) * this.stepHeight; // Arc upwards then downwards
const currentTargetPos_swing = new THREE.Vector3(interpolatedSwingX, interpolatedSwingY, interpolatedSwingZ);
this.applyIK(leg, currentTargetPos_swing);
if (swingProgress >= 1) {
this.legStates[i] = 'PLANTING';
this.legTimers[i] = 0;
}
break;
case 'PLANTING':
const plantProgress = Math.min(1, this.legTimers[i] / (this.stepSpeed * 0.2)); // 20% of step time for planting
const finalTargetY = this.legDesiredTargets[i].y;
const interpolatedPlantPos = new THREE.Vector3(
this.legDesiredTargets[i].x,
THREE.MathUtils.lerp(currentFootWorldPos.y, finalTargetY, plantProgress), // Lerp actual foot Y
this.legDesiredTargets[i].z
);
this.applyIK(leg, interpolatedPlantPos);
if (plantProgress >= 1) {
this.legCurrentTargets[i].copy(this.legDesiredTargets[i]); // Update current target
this.legStates[i] = 'IDLE';
this.legTimers[i] = 0;
}
break;
}
}
this.updateBodyHeight(); // Adjust body height in every frame
}
// Sets the desired movement direction based on input
move(direction) {
this.moveDirection.copy(direction).normalize();
this.velocity.copy(this.moveDirection).multiplyScalar(this.speed);
}
// Stops the spider's movement
stop() {
this.velocity.set(0, 0, 0);
this.moveDirection.set(0, 0, 0);
}
}
// --- Keyboard Input Handling ---
const keys = {
w: false,
a: false,
s: false,
d: false,
};
window.addEventListener('keydown', (event) => {
if (keys.hasOwnProperty(event.key.toLowerCase())) {
keys[event.key.toLowerCase()] = true;
}
});
window.addEventListener('keyup', (event) => {
if (keys.hasOwnProperty(event.key.toLowerCase())) {
keys[event.key.toLowerCase()] = false;
}
});
function handleKeyboardInput(spider) {
const direction = new THREE.Vector3();
if (keys.w) direction.z -= 1; // Forward (local Z)
if (keys.s) direction.z += 1; // Backward (local Z)
if (keys.a) direction.x -= 1; // Left (local X)
if (keys.d) direction.x += 1; // Right (local X)
if (direction.lengthSq() > 0) {
direction.normalize();
// Transform input direction from global XZ to spider's local XZ
// Spider's forward is its local +Z. So we interpret W/S along local Z, A/D along local X.
spider.move(direction);
} else {
spider.stop();
}
}
// --- Initialize Spider ---
const spider = new Spider(scene, terrain, obstacles);
// --- Animation Loop ---
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const delta = clock.getDelta();
handleKeyboardInput(spider);
spider.update(delta); // Update spider animation and movement
controls.update(); // Only required if controls.enableDamping is set to true
renderer.render(scene, camera);
}
animate();
// --- Handle Window Resize ---
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
</script>
</body>
</html>