Create an interactive 3D web application using Three.js to demonstrate advanced…
- User
Create an interactive 3D web application using Three.js to demonstrate advanced procedurally walking animated creature using three.js, rapier, and a three.js IK library if that is helpful to use.
Use CDNs.
- Assistant
Let's create an interactive 3D web application featuring a procedurally walking animated creature using Three.js, Rapier (for physics), and IK (Inverse Kinematics) concepts. We'll use CDNs for all dependencies to make it easy to run in a browser.
This example will create a spider-like creature with procedural leg movement, physics-based interaction with the ground, and basic user controls. We'll use Three.js for rendering, Rapier for physics simulation, and implement a simple IK system for leg movement.
Here's the complete code for an HTML file that you can save and open in a browser:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Procedural Walking Creature</title> <style> body { margin: 0; overflow: hidden; } canvas { display: block; } #info { position: absolute; top: 10px; left: 10px; color: white; font-family: Arial, sans-serif; background: rgba(0, 0, 0, 0.5); padding: 10px; border-radius: 5px; } </style> </head> <body> <div id="info"> Controls:<br> W/A/S/D - Move creature<br> Space - Jump<br> Mouse - Look around </div> <!-- Three.js --> <script type="importmap"> { "imports": { "three": "https://unpkg.com/three@0.156.1/build/three.module.js", "three/addons/": "https://unpkg.com/three@0.156.1/examples/jsm/" } } </script> <!-- Rapier Physics --> <script type="module" src="https://cdn.jsdelivr.net/npm/@dimforge/rapier3d-compat@0.11.2/dist/rapier.es.js"></script> <script type="module"> import * as THREE from 'three'; import { OrbitControls } from 'three/addons/controls/OrbitControls.js'; import RAPIER from 'https://cdn.jsdelivr.net/npm/@dimforge/rapier3d-compat@0.11.2/dist/rapier.es.js'; // Initialize Three.js 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); // Initialize Rapier Physics let world; let creatureBody; let groundCollider; // Creature properties const creature = { body: null, legs: [], legTargets: [], speed: 0.1, legStepDistance: 0.5, legHeight: 0.3 }; // Input handling const keys = {}; document.addEventListener('keydown', (e) => keys[e.code] = true); document.addEventListener('keyup', (e) => keys[e.code] = false); // Initialize scene async function init() { // Initialize Rapier await RAPIER.init(); world = new RAPIER.World({ x: 0, y: -9.81, z: 0 }); // Add lights const ambientLight = new THREE.AmbientLight(0x404040); scene.add(ambientLight); const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5); directionalLight.position.set(1, 1, 1); scene.add(directionalLight); // Create ground const groundGeometry = new THREE.PlaneGeometry(100, 100); const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x888888 }); const ground = new THREE.Mesh(groundGeometry, groundMaterial); ground.rotation.x = -Math.PI / 2; scene.add(ground); // Add ground physics groundCollider = world.createCollider( RAPIER.ColliderDesc.cuboid(50, 0.1, 50) .setTranslation(0, -0.1, 0) ); // Create creature createCreature(); // Camera setup camera.position.set(0, 2, 5); // Start animation animate(); } function createCreature() { // Create body const bodyGeometry = new THREE.SphereGeometry(0.5, 32, 32); const bodyMaterial = new THREE.MeshStandardMaterial({ color: 0xff0000 }); creature.body = new THREE.Mesh(bodyGeometry, bodyMaterial); scene.add(creature.body); // Add physics to body const rigidBodyDesc = RAPIER.RigidBodyDesc.dynamic() .setTranslation(0, 1, 0); creatureBody = world.createRigidBody(rigidBodyDesc); const colliderDesc = RAPIER.ColliderDesc.ball(0.5) .setRestitution(0.5) .setFriction(1.0); world.createCollider(colliderDesc, creatureBody); // Create legs (4 legs for simplicity) const legCount = 4; const legLength = 1; for (let i = 0; i < legCount; i++) { const angle = (i / legCount) * Math.PI * 2; const leg = createLeg(legLength); leg.position.set( Math.cos(angle) * 0.3, 0, Math.sin(angle) * 0.3 ); creature.body.add(leg); creature.legs.push(leg); // Create leg target const target = new THREE.Object3D(); target.position.set( Math.cos(angle) * legLength, -0.5, Math.sin(angle) * legLength ); creature.legTargets.push(target); scene.add(target); } } function createLeg(length) { const legGroup = new THREE.Group(); // Upper leg const upperLegGeometry = new THREE.CylinderGeometry(0.05, 0.05, length/2, 8); const legMaterial = new THREE.MeshStandardMaterial({ color: 0x00ff00 }); const upperLeg = new THREE.Mesh(upperLegGeometry, legMaterial); upperLeg.position.y = -length/4; legGroup.add(upperLeg); // Lower leg const lowerLegGeometry = new THREE.CylinderGeometry(0.05, 0.05, length/2, 8); const lowerLeg = new THREE.Mesh(lowerLegGeometry, legMaterial); lowerLeg.position.y = -length/2; upperLeg.add(lowerLeg); return legGroup; } function updateLegIK() { creature.legs.forEach((leg, index) => { const target = creature.legTargets[index]; const targetWorldPos = target.getWorldPosition(new THREE.Vector3()); const legWorldPos = leg.getWorldPosition(new THREE.Vector3()); // Simple two-bone IK const upperLeg = leg.children[0]; const lowerLeg = upperLeg.children[0]; const legLength = 1; // Calculate direction to target const direction = targetWorldPos.clone().sub(legWorldPos).normalize(); // Calculate angles using law of cosines const d = targetWorldPos.distanceTo(legWorldPos); const l1 = legLength/2; const l2 = legLength/2; if (d > l1 + l2) { // Target is too far, stretch towards it upperLeg.lookAt(targetWorldPos); lowerLeg.rotation.set(0, 0, 0); } else { // Calculate angles const cosAngle0 = Math.min(1, Math.max(-1, (d*d + l1*l1 - l2*l2) / (2*d*l1))); const angle0 = Math.acos(cosAngle0); const cosAngle1 = Math.min(1, Math.max(-1, (l1*l1 + l2*l2 - d*d) / (2*l1*l2))); const angle1 = Math.acos(cosAngle1); // Apply rotations upperLeg.lookAt(targetWorldPos); upperLeg.rotation.x += angle0; lowerLeg.rotation.x = Math.PI - angle1; } }); } function updateLegTargets() { creature.legTargets.forEach((target, index) => { const leg = creature.legs[index]; const legWorldPos = leg.getWorldPosition(new THREE.Vector3()); const targetWorldPos = target.getWorldPosition(new THREE.Vector3()); // Raycast to find ground position const ray = new RAPIER.Ray( { x: legWorldPos.x, y: legWorldPos.y, z: legWorldPos.z }, { x: 0, y: -1, z: 0 } ); const hit = world.castRay(ray, 10, true); if (hit) { const hitPoint = ray.pointAt(hit.toi); const distance = targetWorldPos.distanceTo(hitPoint); if (distance > creature.legStepDistance) { // Move target to new position target.position.set( hitPoint.x - creature.body.position.x, hitPoint.y, hitPoint.z - creature.body.position.z ); } } }); } function handleInput() { const velocity = creatureBody.linvel(); let movement = new THREE.Vector3(); if (keys['KeyW']) movement.z -= creature.speed; if (keys['KeyS']) movement.z += creature.speed; if (keys['KeyA']) movement.x -= creature.speed; if (keys['KeyD']) movement.x += creature.speed; if (keys['Space']) { if (Math.abs(velocity.y) < 0.1) { // Only jump if on ground creatureBody.setLinvel({ x: velocity.x, y: 5, z: velocity.z }, true); } } // Apply movement creatureBody.setLinvel({ x: movement.x, y: velocity.y, z: movement.z }, true); } function animate() { requestAnimationFrame(animate); // Step physics world.step(); // Update creature position const position = creatureBody.translation(); creature.body.position.set(position.x, position.y, position.z); // Handle input handleInput(); // Update leg movement updateLegTargets(); updateLegIK(); // Update camera camera.position.set( position.x, position.y + 2, position.z + 5 ); camera.lookAt(position.x, position.y, position.z); renderer.render(scene, camera); } // Handle window resize window.addEventListener('resize', () => { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); }); init(); </script> </body> </html>Explanation of the Code:
-
Dependencies:
- Three.js: Used for rendering the 3D scene, loaded via a CDN with an import map.
- Rapier: A physics engine for simulating gravity, collisions, and raycasting, loaded via a CDN.
- No explicit IK library is used; instead, a simple two-bone IK solver is implemented manually for the legs.
-
Scene Setup:
- A basic scene is created with a ground plane, ambient and directional lighting, and a camera.
- Rapier physics is initialized with gravity, and a ground collider is added.
-
Creature Creation:
- The creature has a spherical body and four legs, each composed of two segments (upper and lower leg).
- The body is a dynamic physics object, allowing it to fall and interact with the ground.
- Each leg has a target position, which is updated procedurally to simulate walking.
-
Procedural Walking:
- Leg Targets: Each leg has a target position on the ground, determined by raycasting downward from the leg's base. If the target is too far from the current position, it moves to a new position, simulating a step.
- IK (Inverse Kinematics): A simple two-bone IK solver is implemented to position the legs so they reach their targets. This uses the law of cosines to calculate joint angles.
-
Input Handling:
- W/A/S/D keys move the creature forward, backward, left, and right.
- Spacebar makes the creature jump (if it's on the ground).
- The camera follows the creature automatically.
-
Physics:
- Rapier handles gravity, collisions, and raycasting for ground detection.
- The creature's body is a dynamic rigid body, and its movement is controlled by setting linear velocity.
-
Rendering:
- The scene is rendered using Three.js, with the camera following the creature.
How to Run:
- Save the code as an HTML file (e.g.,
creature.html). - Open it in a modern web browser (Chrome, Firefox, etc.).
- Ensure you have an internet connection, as the dependencies are loaded from CDNs.
Notes:
- This is a simplified example. For a more complex creature, you might want to:
- Add more legs (e.g., 6 or 8 for a more spider-like creature).
- Implement a more sophisticated gait system (e.g., alternating legs in a specific pattern).
- Use a dedicated IK library like
three-ik(though it may require local setup, as it's not available via CDN).
- The physics simulation might need tuning (e.g., friction, restitution) for more realistic movement.
- For better performance, consider using a local development server instead of loading directly from a file (due to CORS restrictions with some CDNs).
This example provides a foundation for creating more complex procedural animations and can be extended with additional features like terrain adaptation, obstacle avoidance, or more realistic physics.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.