Project Goal: Create an interactive 3D web application using Three.js to demonstrate…
- User
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.
Output as one unified .html file.
https://cdn.jsdelivr.net/npm/three-ik@0.1.0/build/three-ik.min.js
Assistant
<!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-IK</title> <style> body { margin: 0; overflow: hidden; background-color: #1a1a1a; color: #fff; font-family: sans-serif; } canvas { display: block; } #info { position: absolute; top: 10px; left: 10px; background-color: rgba(0,0,0,0.7); padding: 10px; border-radius: 5px; } </style> </head> <body> <div id="info"> <h1>Procedural Spider Animation</h1> <p>Use WASD keys to move the spider.</p> <p>Use Mouse to orbit the camera.</p> <p>Spider Legs adapt to terrain!</p> </div> <script src="https://cdn.jsdelivr.net/npm/three@0.150.1/build/three.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/three-ik@0.1.0/build/three-ik.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/three/examples/js/controls/OrbitControls.js"></script> <script src="https://cdn.jsdelivr.net/npm/three/examples/js/math/SimplexNoise.js"></script> <script> // === Global Variables === let scene, camera, renderer, controls, clock; let ground; let spider; // Spider movement state const moveSpeed = 2.0; const rotationSpeed = Math.PI; // Radians per second let moveForward = false; let moveBackward = false; let moveLeft = false; let moveRight = false; // === Initialization === function init() { // Scene setup scene = new THREE.Scene(); scene.background = new THREE.Color(0x1a1a1a); scene.fog = new THREE.Fog(0x1a1a1a, 1, 60); // Camera setup camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100); camera.position.set(10, 10, 15); // Initial camera position // Renderer setup renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(window.innerWidth, window.innerHeight); renderer.shadowMap.enabled = true; // Enable shadows for better visuals renderer.shadowMap.type = THREE.PCFSoftShadowMap; document.body.appendChild(renderer.domElement); // Orbit Controls setup controls = new THREE.OrbitControls(camera, renderer.domElement); controls.target.set(0, 2, 0); // Camera looks at this point initially controls.enableDamping = true; // Smooth camera movement controls.dampingFactor = 0.05; controls.screenSpacePanning = false; controls.minDistance = 5; controls.maxDistance = 50; // Lighting setup const ambientLight = new THREE.AmbientLight(0xffffff, 0.6); scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0); directionalLight.position.set(15, 30, 10); directionalLight.castShadow = true; directionalLight.shadow.mapSize.width = 1024; directionalLight.shadow.mapSize.height = 1024; directionalLight.shadow.camera.near = 1; directionalLight.shadow.camera.far = 40; directionalLight.shadow.camera.left = -20; directionalLight.shadow.camera.right = 20; directionalLight.shadow.camera.top = 20; directionalLight.shadow.camera.bottom = -20; scene.add(directionalLight); // Clock for delta time calculation clock = new THREE.Clock(); // Create ground, obstacles, and spider createGround(); createObstacles(); createSpider(); // Event listeners for window resize and keyboard input window.addEventListener('resize', onWindowResize, false); document.addEventListener('keydown', onKeyDown); document.addEventListener('keyup', onKeyUp); // Start the animation loop animate(); } // === Ground Creation === function createGround() { const terrainSize = 50; const terrainDetail = 1; // Lower detail for better performance const heightMultiplier = 6; const noiseScale = 0.05; // Adjust for terrain bumpiness // Use BufferGeometry for custom vertex manipulation const geometry = new THREE.PlaneGeometry(terrainSize, terrainSize, terrainSize - 1, terrainSize - 1); const vertices = geometry.attributes.position.array; const simplex = new THREE.SimplexNoise(); // Use SimplexNoise for smoother terrain for (let i = 0; i < vertices.length; i += 3) { const x = vertices[i]; const z = vertices[i + 2]; // Use z for depth axis // Combine multiple noise layers for more complex terrain let noiseVal = simplex.noise(x * noiseScale, z * noiseScale) * 0.5; noiseVal += simplex.noise(x * noiseScale * 2, z * noiseScale * 2) * 0.25; noiseVal += simplex.noise(x * noiseScale * 4, z * noiseScale * 4) * 0.125; // Apply height variation vertices[i + 1] = noiseVal * heightMultiplier; } geometry.attributes.position.needsUpdate = true; geometry.computeVertexNormals(); // Important for correct lighting const material = new THREE.MeshStandardMaterial({ color: 0x4a4a4a, side: THREE.DoubleSide }); ground = new THREE.Mesh(geometry, material); ground.rotation.x = -Math.PI / 2; // Rotate plane to be horizontal ground.position.y = -0.1; // Place slightly below origin ground.receiveShadow = true; // Allow ground to receive shadows scene.add(ground); } // === Obstacle Creation === function createObstacles() { const obstacleMaterial = new THREE.MeshStandardMaterial({ color: 0x882222 }); // Sphere obstacle const sphereGeometry = new THREE.SphereGeometry(1.2, 24, 24); const sphere = new THREE.Mesh(sphereGeometry, obstacleMaterial); sphere.position.set(7, getGroundHeight(7, 5) + 1.2, 5); sphere.castShadow = true; sphere.receiveShadow = true; scene.add(sphere); // Box obstacle const boxGeometry = new THREE.BoxGeometry(2, 2.5, 2); const box = new THREE.Mesh(boxGeometry, obstacleMaterial); box.position.set(-8, getGroundHeight(-8, 8) + 1.25, 8); box.castShadow = true; box.receiveShadow = true; scene.add(box); // Another Sphere obstacle const sphere2 = new THREE.Mesh(sphereGeometry, obstacleMaterial); sphere2.position.set(0, getGroundHeight(0, -12) + 1.2, -12); sphere2.castShadow = true; sphere2.receiveShadow = true; scene.add(sphere2); } // Helper function to get ground height at a specific point function getGroundHeight(x, z) { if (!ground) return 0; const vertices = ground.geometry.attributes.position.array; const planeSize = ground.geometry.parameters.width; const segmentCount = ground.geometry.parameters.widthSegments; // Calculate grid indices based on position relative to the plane center const halfSize = planeSize / 2; const xIndex = Math.floor(((x + halfSize) / planeSize) * (segmentCount + 1)); const zIndex = Math.floor(((z + halfSize) / planeSize) * (segmentCount + 1)); // Ensure indices are within bounds if (xIndex < 0 || xIndex > segmentCount || zIndex < 0 || zIndex > segmentCount) { return 0; // Outside the plane } // Calculate the index in the flat vertices array // Vertices are stored row by row (z changes faster) const vertexIndex = (zIndex * (segmentCount + 1) + xIndex) * 3; // Check if vertexIndex is valid if (vertexIndex < 0 || vertexIndex >= vertices.length) { console.warn(`Invalid vertex index calculated: ${vertexIndex}`); return 0; } // Return the y-coordinate (height) return vertices[vertexIndex + 1]; } // === Spider Creation === function createSpider() { spider = new THREE.Object3D(); // Use Object3D as the spider's root spider.position.set(0, 5, 0); // Initial position above ground scene.add(spider); // Spider Body const bodyGeometry = new THREE.SphereGeometry(1.5, 32, 32); const bodyMaterial = new THREE.MeshStandardMaterial({ color: 0x222222 }); const body = new THREE.Mesh(bodyGeometry, bodyMaterial); body.position.y = 0; // Center of the spider's coordinate system body.castShadow = true; spider.add(body); // Leg attachment points relative to the spider's body center // Coordinates: (x: side, z: forward/backward) const legOffsets = [ // Group 0 (Moves when spider moves forward) { x: -1.0, z: 1.5, side: 'L', index: 1, group: 0 }, // Front-Left { x: 1.2, z: 0.5, side: 'R', index: 2, group: 0 }, // Mid-Right { x: -1.0, z: -0.5, side: 'L', index: 5, group: 0 }, // RearMid-Left { x: -0.8, z: -1.5, side: 'L', index: 7, group: 0 }, // Rear-Left // Group 1 (Moves when spider moves backward / opposite) { x: 1.0, z: 1.5, side: 'R', index: 0, group: 1 }, // Front-Right { x: -1.2, z: 0.5, side: 'L', index: 3, group: 1 }, // Mid-Left { x: 1.0, z: -0.5, side: 'R', index: 4, group: 1 }, // RearMid-Right { x: 0.8, z: -1.5, side: 'R', index: 6, group: 1 }, // Rear-Right ]; const segmentLength = 1.8; const segmentRadius = 0.15; const legBaseHeight = 0.4; // Height of the hip joint from the body's bottom const legMaterial = new THREE.MeshStandardMaterial({ color: 0x111111 }); spider.legs = []; // Store leg data spider.ikChains = []; // Store IK chains for (let i = 0; i < 8; i++) { const offsetData = legOffsets[i]; // Create a parent Object3D for each leg's skeleton const legObject = new THREE.Object3D(); // Position the leg's base (hip joint) relative to the spider's root legObject.position.set(offsetData.x, -body.geometry.parameters.radius + legBaseHeight, offsetData.z); spider.add(legObject); // Define the skeleton (bones) const hipBone = new THREE.Bone(); hipBone.position.set(0, 0, 0); // Relative to legObject const kneeBone = new THREE.Bone(); kneeBone.position.set(0, -segmentLength, 0); // Segment points downwards const footBone = new THREE.Bone(); // End effector footBone.position.set(0, -segmentLength, 0); // Segment points downwards hipBone.add(kneeBone); kneeBone.add(footBone); legObject.add(hipBone); // Add the hip bone to the leg's base // Create visual representation (cylinders) for segments and attach them to bones // Hip Segment const hipGeo = new THREE.CylinderGeometry(segmentRadius, segmentRadius, segmentLength, 12, 1, false); const hipMesh = new THREE.Mesh(hipGeo, legMaterial); hipMesh.position.set(0, -segmentLength / 2, 0); // Center the cylinder along the bone hipMesh.rotation.x = Math.PI / 2; // Align cylinder's length (Y-axis) with bone direction hipBone.add(hipMesh); // Knee Segment const kneeGeo = new THREE.CylinderGeometry(segmentRadius, segmentRadius, segmentLength, 12, 1, false); const kneeMesh = new THREE.Mesh(kneeGeo, legMaterial); kneeMesh.position.set(0, -segmentLength / 2, 0); // Center the cylinder along the bone kneeMesh.rotation.x = Math.PI / 2; // Align cylinder's length (Y-axis) with bone direction kneeBone.add(kneeMesh); // IK Setup const IKtarget = new THREE.Object3D(); // Target for the foot IK IKtarget.position.set(0, -segmentLength, 0); // Default position relative to foot bone origin legObject.add(IKtarget); // Add target to the leg's parent Object3D // Create the IK chain const chain = new IK.Chain(); // Add segments with constraints. Constraints limit the rotation of joints. // BallSocketConstraint(x, y, z limits) // Primary bend axis for legs is typically X or Y depending on orientation. Let's assume X for forward/backward bend. chain.add(new IK.Segment(hipBone, new IK.IKBallSocketConstraint( { max: Math.PI * 0.7, min: -Math.PI * 0.7 }, // Limit forward/backward bend (X) { max: Math.PI * 0.2, min: -Math.PI * 0.2 }, // Limit twist (Y) { max: Math.PI * 0.7, min: -Math.PI * 0.7 } // Limit side bend (Z) ))); chain.add(new IK.Segment(kneeBone, new IK.IKBallSocketConstraint( { max: Math.PI * 0.8, min: 0 }, // Limit forward bend (X), prevent folding backward { max: Math.PI * 0.2, min: -Math.PI * 0.2 }, // Limit twist (Y) { max: Math.PI * 0.2, min: -Math.PI * 0.2 } // Limit side bend (Z) ))); chain.add(new IK.Segment(footBone)); // End effector, no constraints needed const solver = new IK.CCDParser(); // Or IK.JacobianParser() for potentially smoother results spider.legs.push({ index: i, offsetData, // Original offset relative to spider body center legObject, // Parent Object3D for the leg's bones hipBone, kneeBone, footBone, // Bones IKtarget, // IK target Object3D chain, // IK chain solver, // IK solver targetWorldPos: new THREE.Vector3(), // Calculated world target position for the foot stepHeight: 0.8, // How high the leg lifts during movement isMoving: false, // Flag if leg is currently striding group: offsetData.group // Gait group assignment }); } } // Helper function to update the visual segments (cylinders) to match bone orientations function updateLegSegmentVisuals(leg) { const segmentLength = 1.5; // Assumed length for visual cylinders // Update hip segment mesh const hipOrigin = new THREE.Vector3(); leg.hipBone.getWorldPosition(hipOrigin); // World position of the hip joint origin const kneeOrigin = new THREE.Vector3(); leg.kneeBone.getWorldPosition(kneeOrigin); // World position of the knee joint origin const hipSegmentDir = kneeOrigin.clone().sub(hipOrigin).normalize(); // Direction from hip to knee // Calculate the midpoint for the cylinder's center const hipSegmentMidpoint = hipOrigin.clone().add(hipSegmentDir.multiplyScalar(segmentLength / 2)); const hipSegmentMesh = leg.hipBone.children[0]; // Assume mesh is the first child of the bone if (hipSegmentMesh) { hipSegmentMesh.position.copy(hipSegmentMidpoint); // Align the cylinder's local Y axis with the bone's direction vector hipSegmentMesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), hipSegmentDir); } // Update knee segment mesh const kneeOrigin_ = new THREE.Vector3(); // Use kneeOrigin_ to avoid potential naming conflicts leg.kneeBone.getWorldPosition(kneeOrigin_); // World position of the knee joint origin const footOrigin = new THREE.Vector3(); leg.footBone.getWorldPosition(footOrigin); // World position of the foot joint origin (end effector) const kneeSegmentDir = footOrigin.clone().sub(kneeOrigin_).normalize(); // Direction from knee to foot // Calculate the midpoint for the cylinder's center const kneeSegmentMidpoint = kneeOrigin_.clone().add(kneeSegmentDir.multiplyScalar(segmentLength / 2)); const kneeSegmentMesh = leg.kneeBone.children[0]; // Assume mesh is the first child of the bone if (kneeSegmentMesh) { kneeSegmentMesh.position.copy(kneeSegmentMidpoint); // Align the cylinder's local Y axis with the bone's direction vector kneeSegmentMesh.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), kneeSegmentDir); } } // === Spider Animation Logic (Gait and IK) === function updateSpiderAnimation(delta) { const gaitSpeed = 4.0; // Controls how fast the legs move through their cycle const groundRaycastOffset = 3.0; // Height from which to cast ray downwards for ground detection const time = performance.now() * 0.001; // Current time in seconds const isSpiderMoving = moveForward || moveBackward || moveLeft || moveRight; // Calculate target positions for all legs based on spider movement and gait for (const leg of spider.legs) { const legBaseWorldPos = new THREE.Vector3(); leg.legObject.getWorldPosition(legBaseWorldPos); // World position of the leg's base (hip joint) // Calculate the desired horizontal position of the leg's foot relative to the spider's body center // Start with the leg's initial offset, then apply the spider's rotation let desiredFootOffset = new THREE.Vector3(leg.offsetData.x, 0, leg.offsetData.z); desiredFootOffset.applyQuaternion(spider.quaternion); let targetWorldPos = spider.position.clone(); // Start with spider's current position // Gait calculation: Determine if the leg should be moving forward/backward in this cycle const cycleProgress = (time * gaitSpeed) + leg.phase; // Time adjusted by phase for staggered movement const stepProgress = Math.sin(cycleProgress); // Value from -1 (back) to 1 (forward) let legShouldMove = false; // Determine movement based on group and step progress if (isSpiderMoving) { if (leg.group === 0) { // Group 0 moves forward when stepProgress > 0 legShouldMove = stepProgress > 0; } else { // Group 1 moves forward when stepProgress < 0 legShouldMove = stepProgress < 0; } } leg.isMoving = legShouldMove; if (legShouldMove) { // Leg is striding: Calculate its target position in space const strideMagnitude = 1.8; // How far the leg reaches during a stride const spiderForwardDir = new THREE.Vector3(0, 0, 1).applyQuaternion(spider.quaternion); const spiderRightDir = new THREE.Vector3(1, 0, 0).applyQuaternion(spider.quaternion); // Calculate the base stride position let strideBasePos = spider.position.clone(); // Adjust stride based on leg's original position (forward/backward) and group const forwardMovement = strideMagnitude * (leg.offsetData.z > 0 ? 1 : -1); if (leg.group === 0) { // Group 0 reaches forward when spider moves forward strideBasePos.add(spiderForwardDir.multiplyScalar(forwardMovement)); } else { // Group 1 reaches backward when spider moves forward strideBasePos.add(spiderForwardDir.multiplyScalar(-forwardMovement)); } // Add side offset based on spider's orientation strideBasePos.add(spiderRightDir.multiplyScalar(leg.offsetData.x)); // Calculate vertical lift based on step progress const verticalLift = leg.stepHeight * Math.abs(stepProgress); // Raycast to find ground height at the target stride position const raycaster = new THREE.Raycaster(); const rayOrigin = strideBasePos.clone().add(new THREE.Vector3(0, groundRaycastOffset, 0)); raycaster.set(rayOrigin, new THREE.Vector3(0, -1, 0)); // Ray downwards const intersects = raycaster.intersectObject(ground); if (intersects.length > 0) { // Position the leg target on the ground, adjusted by vertical lift leg.targetWorldPos.set( strideBasePos.x, intersects[0].point.y + verticalLift, strideBasePos.z ); } else { // If no ground found, use a default position below the spider leg.targetWorldPos.set( strideBasePos.x, spider.position.y - leg.offsetData.z - 1.0 + verticalLift, // Estimate height strideBasePos.z ); } } else { // Leg is planted: Keep it on the ground at its current horizontal position relative to the spider // Calculate the target horizontal position based on spider's current orientation and leg's offset const attachmentPointWorld = new THREE.Vector3(leg.offsetData.x, 0, leg.offsetData.z) .applyQuaternion(spider.quaternion) .add(spider.position); // Raycast to find the ground contact point for the static leg const raycaster = new THREE.Raycaster(); const rayOrigin = attachmentPointWorld.clone().add(new THREE.Vector3(0, groundRaycastOffset, 0)); raycaster.set(rayOrigin, new THREE.Vector3(0, -1, 0)); // Ray downwards const intersects = raycaster.intersectObject(ground); if (intersects.length > 0) { // Place the target on the ground surface leg.targetWorldPos.set( attachmentPointWorld.x, intersects[0].point.y, attachmentPointWorld.z ); } else { // Default position if no ground is found leg.targetWorldPos.set( attachmentPointWorld.x, spider.position.y - leg.offsetData.z - 1.0, attachmentPointWorld.z ); } } } // Solve IK for all legs using the calculated target positions for (const leg of spider.legs) { // Set the IK target's position (relative to its parent, which is the spider root) leg.IKtarget.position.copy(leg.targetWorldPos).sub(spider.position); // Solve the IK chain leg.chain.solve(); // Update the visual segments to match the current bone orientations updateLegSegmentVisuals(leg); } } // === Spider Movement Control === function updateSpiderMovement(delta) { let moveDirection = new THREE.Vector3(0, 0, 0); // Direction relative to spider's local axes if (moveForward) moveDirection.z -= moveSpeed * delta; if (moveBackward) moveDirection.z += moveSpeed * delta; if (moveLeft) moveDirection.x -= moveSpeed * delta; if (moveRight) moveDirection.x += moveSpeed * delta; // If there's input, update spider's position and rotation if (moveDirection.lengthSq() > 0.01) { // Apply movement based on spider's current orientation spider.position.add(moveDirection.clone().applyQuaternion(spider.quaternion)); // Calculate rotation to face the direction of movement const targetForward = new THREE.Vector3(0, 0, -1); // Negative Z is forward in Three.js standard orientation const currentForward = targetForward.clone().applyQuaternion(spider.quaternion); const moveDirXZ = new THREE.Vector3(moveDirection.x, 0, moveDirection.z).normalize(); if (moveDirXZ.lengthSq() > 0.01) { const angleToMove = Math.atan2(moveDirXZ.x, moveDirXZ.z); const targetQuaternion = new THREE.Quaternion(); targetQuaternion.setFromAxisAngle(new THREE.Vector3(0, 1, 0), angleToMove); // Smoothly rotate the spider towards the movement direction spider.quaternion.slerp(targetQuaternion, rotationSpeed * delta); } } } // === Animation Loop === function animate() { requestAnimationFrame(animate); const delta = clock.getDelta(); // Get time elapsed since last frame // Update controls (for smooth camera orbiting) controls.update(); // Update spider's movement based on keyboard input updateSpiderMovement(delta); // Update spider's leg animations (gait and ground adaptation) updateSpiderAnimation(delta); // Render the scene renderer.render(scene, camera); } // === Event Handlers === function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); } function onKeyDown(event) { switch (event.keyCode) { case 87: // W moveForward = true; break; case 83: // S moveBackward = true; break; case 65: // A moveLeft = true; break; case 68: // D moveRight = true; break; } } function onKeyUp(event) { switch (event.keyCode) { case 87: // W moveForward = false; break; case 83: // S moveBackward = false; break; case 65: // A moveLeft = false; break; case 68: // D moveRight = false; break; } } // === Start === init(); // Call the initialization function to set up the scene </script> </body> </html>
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
llama-4-maverick-17b-128e-instructCompare side by side →
claude-3-5-haiku-20241022Compare side by side →
gemma-3n-e4b-itCompare side by side →
mistral-medium-2505Compare side by side →
- grok-3-mini-betaCompare side by side →
hunyuan-turbos-20250416Compare side by side →
- o3-miniCompare side by side →
mistral-small-3.1-24b-instruct-2503Compare side by side →
gemini-2.5-flash-lite-preview-06-17-thinkingCompare side by side →
claude-3-7-sonnet-20250219Compare side by side →
gemini-2.5-proCompare side by side →