html Copy code
<!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 - Three.js</title>
<style>
body {
margin: 0;
overflow: hidden;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: #000;
}
#info {
position: absolute;
top: 10px;
left: 10px;
color: white;
background: linear-gradient(135deg, rgba(0, 0, 0, 0.7), rgba(20, 20, 40, 0.7));
padding: 15px 20px;
border-radius: 10px;
font-size: 14px;
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
}
#controls {
position: absolute;
top: 10px;
right: 10px;
background: linear-gradient(135deg, rgba(0, 0, 0, 0.7), rgba(20, 20, 40, 0.7));
padding: 15px;
border-radius: 10px;
color: white;
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
}
.control-group {
margin-bottom: 10px;
}
label {
display: inline-block;
width: 120px;
font-size: 12px;
}
input[type="range"] {
width: 100px;
vertical-align: middle;
}
.value {
display: inline-block;
width: 40px;
text-align: right;
font-size: 12px;
color: #88ccff;
}
button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: none;
color: white;
padding: 8px 16px;
border-radius: 5px;
cursor: pointer;
font-size: 12px;
margin: 2px;
transition: transform 0.2s;
}
button:hover {
transform: translateY(-1px);
}
#stats {
position: absolute;
bottom: 10px;
left: 10px;
color: white;
background: linear-gradient(135deg, rgba(0, 0, 0, 0.7), rgba(20, 20, 40, 0.7));
padding: 10px 15px;
border-radius: 10px;
font-size: 12px;
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
}
</style>
</head>
<body>
<div id="info">
<h3 style="margin: 0 0 10px 0;">Procedural Walking Creature</h3>
<div>Click to spawn obstacles • WASD to move • Mouse to look</div>
</div>
<div id="controls">
<h4 style="margin: 0 0 10px 0;">Controls</h4>
<div class="control-group">
<label>Speed:</label>
<input type="range" id="speedSlider" min="0" max="2" step="0.1" value="1">
<span class="value" id="speedValue">1.0</span>
</div>
<div class="control-group">
<label>Leg Height:</label>
<input type="range" id="heightSlider" min="0.5" max="2" step="0.1" value="1">
<span class="value" id="heightValue">1.0</span>
</div>
<div class="control-group">
<label>Gait:</label>
<input type="range" id="gaitSlider" min="0.5" max="2" step="0.1" value="1">
<span class="value" id="gaitValue">1.0</span>
</div>
<div class="control-group">
<button onclick="togglePause()">Pause/Resume</button>
<button onclick="resetCreature()">Reset</button>
</div>
</div>
<div id="stats">
<div>FPS: <span id="fps">60</span></div>
<div>Position: <span id="position">0, 0, 0</span></div>
</div>
<!-- Three.js CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!-- Rapier Physics CDN -->
<script src="https://cdn.jsdelivr.net/npm/@dimforge/rapier3d-compat@0.11.2/rapier.js"></script>
<!-- Three.js IK Solver (simple implementation) -->
<script>
// Simple CCD IK solver for Three.js
class CCDIKSolver {
constructor(mesh, iks) {
this.mesh = mesh;
this.iks = iks || [];
}
update() {
const q = new THREE.Quaternion();
const targetPos = new THREE.Vector3();
const effectorPos = new THREE.Vector3();
const linkPos = new THREE.Vector3();
const axis = new THREE.Vector3();
const vector = new THREE.Vector3();
for (let i = 0; i < this.iks.length; i++) {
const ik = this.iks[i];
const bones = ik.links.map(link => this.mesh.getObjectByName(link.name));
const target = this.mesh.getObjectByName(ik.target.name);
if (!target || bones.some(b => !b)) continue;
for (let j = 0; j < ik.iteration; j++) {
let rotated = false;
for (let k = 0; k < bones.length; k++) {
const bone = bones[k];
const link = ik.links[k];
// Get positions
target.getWorldPosition(targetPos);
bones[bones.length - 1].getWorldPosition(effectorPos);
bone.getWorldPosition(linkPos);
// Calculate rotation
vector.subVectors(targetPos, linkPos).normalize();
axis.crossVectors(
vector.clone().cross(
vector.subVectors(effectorPos, linkPos).normalize()
),
vector
).normalize();
const angle = vector.angleTo(
vector.subVectors(effectorPos, linkPos).normalize()
);
if (Math.abs(angle) < 1e-5) continue;
q.setFromAxisAngle(axis, Math.min(angle, link.rotationMin || -Infinity, link.rotationMax || Infinity));
bone.quaternion.multiply(q);
// Apply constraints
if (link.limit) {
const euler = new THREE.Euler().setFromQuaternion(bone.quaternion, 'XYZ');
euler.x = Math.max(link.limit.x.min, Math.min(link.limit.x.max, euler.x));
euler.y = Math.max(link.limit.y.min, Math.min(link.limit.y.max, euler.y));
euler.z = Math.max(link.limit.z.min, Math.min(link.limit.z.max, euler.z));
bone.quaternion.setFromEuler(euler);
}
rotated = true;
}
if (!rotated) break;
}
}
}
}
</script>
<script>
// Global variables
let scene, camera, renderer, world;
let creature, ground;
let clock = new THREE.Clock();
let isPaused = false;
let moveSpeed = 1;
let legHeight = 1;
let gaitSpeed = 1;
let keys = {};
let mouseX = 0, mouseY = 0;
let targetPosition = new THREE.Vector3();
let obstacles = [];
let frameCount = 0;
let lastTime = performance.now();
// Initialize the application
async function init() {
// Initialize Rapier physics
await rapier.init();
world = new rapier.World({ x: 0, y: -9.81, z: 0 });
// Create scene
scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x87ceeb, 10, 100);
// Create camera
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 5, 10);
// Create renderer
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.body.appendChild(renderer.domElement);
// Add lights
const ambientLight = new THREE.AmbientLight(0x404040, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.set(10, 20, 5);
directionalLight.castShadow = true;
directionalLight.shadow.camera.left = -20;
directionalLight.shadow.camera.right = 20;
directionalLight.shadow.camera.top = 20;
directionalLight.shadow.camera.bottom = -20;
directionalLight.shadow.mapSize.width = 2048;
directionalLight.shadow.mapSize.height = 2048;
scene.add(directionalLight);
// Add hemisphere light for better ambient
const hemisphereLight = new THREE.HemisphereLight(0x87ceeb, 0x8B4513, 0.3);
scene.add(hemisphereLight);
// Create ground
createGround();
// Create creature
createCreature();
// Add event listeners
window.addEventListener('resize', onWindowResize);
window.addEventListener('keydown', (e) => keys[e.key.toLowerCase()] = true);
window.addEventListener('keyup', (e) => keys[e.key.toLowerCase()] = false);
window.addEventListener('mousemove', (e) => {
mouseX = (e.clientX / window.innerWidth) * 2 - 1;
mouseY = -(e.clientY / window.innerHeight) * 2 + 1;
});
window.addEventListener('click', spawnObstacle);
// Setup controls
setupControls();
// Start animation loop
animate();
}
function createGround() {
// Visual ground
const groundGeometry = new THREE.PlaneGeometry(100, 100, 50, 50);
const groundMaterial = new THREE.MeshStandardMaterial({
color: 0x3a5f3a,
roughness: 0.8,
metalness: 0.2
});
// Add some height variation
const vertices = groundGeometry.attributes.position.array;
for (let i = 0; i < vertices.length; i += 3) {
vertices[i + 2] = Math.sin(vertices[i] * 0.1) * Math.cos(vertices[i + 1] * 0.1) * 0.3;
}
groundGeometry.computeVertexNormals();
ground = new THREE.Mesh(groundGeometry, groundMaterial);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
// Physics ground
const groundBodyDesc = rapier.RigidBodyDesc.fixed();
const groundBody = world.createRigidBody(groundBodyDesc);
const groundColliderDesc = rapier.ColliderDesc.cuboid(50, 0.1, 50);
world.createCollider(groundColliderDesc, groundBody);
}
function createCreature() {
creature = new THREE.Group();
scene.add(creature);
// Body
const bodyGeometry = new THREE.BoxGeometry(2, 0.8, 3);
const bodyMaterial = new THREE.MeshStandardMaterial({
color: 0x8B4513,
roughness: 0.7,
metalness: 0.3
});
const body = new THREE.Mesh(bodyGeometry, bodyMaterial);
body.castShadow = true;
body.receiveShadow = true;
creature.add(body);
// Head
const headGeometry = new THREE.BoxGeometry(1, 0.6, 0.8);
const headMaterial = new THREE.MeshStandardMaterial({
color: 0x654321,
roughness: 0.7,
metalness: 0.3
});
const head = new THREE.Mesh(headGeometry, headMaterial);
head.position.set(0, 0.5, 1.5);
head.castShadow = true;
creature.add(head);
// Eyes
const eyeGeometry = new THREE.SphereGeometry(0.1, 8, 8);
const eyeMaterial = new THREE.MeshStandardMaterial({
color: 0x000000,
emissive: 0x444444
});
const leftEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
leftEye.position.set(-0.2, 0.6, 2);
creature.add(leftEye);
const rightEye = new THREE.Mesh(eyeGeometry, eyeMaterial);
rightEye.position.set(0.2, 0.6, 2);
creature.add(rightEye);
// Create legs
createLegs();
// Physics body for creature
const bodyDesc = rapier.RigidBodyDesc.dynamic()
.setTranslation(0, 2, 0)
.setCanSleep(false);
creature.body = world.createRigidBody(bodyDesc);
const colliderDesc = rapier.ColliderDesc.cuboid(1, 0.4, 1.5)
.setMass(10);
world.createCollider(colliderDesc, creature.body);
// Store leg phase information
creature.legPhase = [0, Math.PI, Math.PI, 0]; // For quadruped gait
creature.legTargets = [
new THREE.Vector3(1, 0, 1.5),
new THREE.Vector3(-1, 0, 1.5),
new THREE.Vector3(1, 0, -1.5),
new THREE.Vector3(-1, 0, -1.5)
];
}
function createLegs() {
creature.legs = [];
// Leg positions relative to body
const legPositions = [
{ x: 1, z: 1.5 }, // Front right
{ x: -1, z: 1.5 }, // Front left
{ x: 1, z: -1.5 }, // Back right
{ x: -1, z: -1.5 } // Back left
];
for (let i = 0; i < 4; i++) {
const leg = createLeg(i);
leg.position.set(legPositions[i].x, -0.4, legPositions[i].z);
creature.add(leg);
creature.legs.push(leg);
}
}
function createLeg(index) {
const leg = new THREE.Group();
// Upper leg
const upperLegGeometry = new THREE.BoxGeometry(0.3, 1.2, 0.3);
const upperLegMaterial = new THREE.MeshStandardMaterial({
color: 0x654321,
roughness: 0.7,
metalness: 0.3
});
const upperLeg = new THREE.Mesh(upperLegGeometry, upperLegMaterial);
upperLeg.position.y = -0.6;
upperLeg.castShadow = true;
leg.add(upperLeg);
// Lower leg
const lowerLegGeometry = new THREE.BoxGeometry(0.25, 1, 0.25);
const lowerLegMaterial = new THREE.MeshStandardMaterial({
color: 0x4a3018,
roughness: 0.7,
metalness: 0.3
});
const lowerLeg = new THREE.Mesh(lowerLegGeometry, lowerLegMaterial);
lowerLeg.position.y = -1.7;
lowerLeg.castShadow = true;
leg.add(lowerLeg);
// Foot
const footGeometry = new THREE.BoxGeometry(0.4, 0.2, 0.6);
const footMaterial = new THREE.MeshStandardMaterial({
color: 0x2a1508,
roughness: 0.9,
metalness: 0.1
});
const foot = new THREE.Mesh(footGeometry, footMaterial);
foot.position.y = -2.3;
foot.castShadow = true;
leg.add(foot);
// Store references for animation
leg.upperLeg = upperLeg;
leg.lowerLeg = lowerLeg;
leg.foot = foot;
leg.index = index;
return leg;
}
function updateCreature(deltaTime) {
if (isPaused) return;
const speed = moveSpeed * gaitSpeed;
const direction = new THREE.Vector3();
// Handle input
if (keys['w']) direction.z += 1;
if (keys['s']) direction.z -= 1;
if (keys['a']) direction.x -= 1;
if (keys['d']) direction.x += 1;
if (direction.length() > 0) {
direction.normalize();
// Rotate creature based on mouse
const targetRotation = Math.atan2(direction.x, direction.z) - mouseX * Math.PI * 0.5;
creature.rotation.y = THREE.MathUtils.lerp(creature.rotation.y, targetRotation, deltaTime * 5);
// Move creature
const moveVector = new THREE.Vector3(
Math.sin(creature.rotation.y) * direction.z + Math.cos(creature.rotation.y) * direction.x,
0,
Math.cos(creature.rotation.y) * direction.z - Math.sin(creature.rotation.y) * direction.x
);
targetPosition.add(moveVector.multiplyScalar(deltaTime * speed * 3));
// Update physics body
const currentPos = creature.body.translation();
const newPos = {
x: THREE.MathUtils.lerp(currentPos.x, targetPosition.x, deltaTime * 5),
y: currentPos.y,
z: THREE.MathUtils.lerp(currentPos.z, targetPosition.z, deltaTime * 5)
};
creature.body.setNextKinematicTranslation(newPos);
// Update leg animations
updateLegs(deltaTime, speed);
}
// Sync visual with physics
const bodyPos = creature.body.translation();
creature.position.set(bodyPos.x, bodyPos.y - 0.4, bodyPos.z);
// Update stats
document.getElementById('position').textContent =
`${bodyPos.x.toFixed(1)}, ${bodyPos.y.toFixed(1)}, ${bodyPos.z.toFixed(1)}`;
}
function updateLegs(deltaTime, speed) {
const legCycle = speed * deltaTime * 3;
creature.legs.forEach((leg, index) => {
// Update leg phase
creature.legPhase[index] += legCycle;
// Calculate leg position based on phase
const phase = creature.legPhase[index];
const liftHeight = Math.sin(phase) * 0.3 * legHeight;
const forwardOffset = Math.cos(phase) * 0.5;
// Apply leg animation
leg.upperLeg.rotation.x = Math.sin(phase) * 0.3;
leg.lowerLeg.rotation.x = Math.sin(phase) * 0.5 + 0.2;
// Adjust foot position
leg.foot.position.y = -2.3 + liftHeight;
// Add slight side-to-side motion
leg.rotation.z = Math.sin(phase * 0.5) * 0.1;
});
// Body bobbing motion
creature.position.y = Math.sin(Date.now() * 0.005 * speed) * 0.05 * legHeight;
creature.rotation.x = Math.sin(Date.now() * 0.003 * speed) * 0.02;
creature.rotation.z = Math.sin(Date.now() * 0.004 * speed) * 0.02;
}
function spawnObstacle(event) {
const mouse = new THREE.Vector2(
(event.clientX / window.innerWidth) * 2 - 1,
-(event.clientY / window.innerHeight) * 2 + 1
);
const raycaster = new THREE.Raycaster();
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObject(ground);
if (intersects.length > 0) {
const point = intersects[0].point;
// Create obstacle
const size = Math.random() * 1 + 0.5;
const obstacleGeometry = new THREE.BoxGeometry(size, size, size);
const obstacleMaterial = new THREE.MeshStandardMaterial({
color: new THREE.Color().setHSL(Math.random(), 0.7, 0.5),
roughness: 0.7,
metalness: 0.3
});
const obstacle = new THREE.Mesh(obstacleGeometry, obstacleMaterial);
obstacle.position.copy(point);
obstacle.position.y = size / 2;
obstacle.castShadow = true;
obstacle.receiveShadow = true;
scene.add(obstacle);
// Physics for obstacle
const bodyDesc = rapier.RigidBodyDesc.dynamic()
.setTranslation(point.x, size / 2, point.z);
obstacle.body = world.createRigidBody(bodyDesc);
const colliderDesc = rapier.ColliderDesc.cuboid(size / 2, size / 2, size / 2)
.setMass(size * 2);
world.createCollider(colliderDesc, obstacle.body);
obstacles.push(obstacle);
// Limit obstacles
if (obstacles.length > 20) {
const oldObstacle = obstacles.shift();
world.removeRigidBody(oldObstacle.body);
scene.remove(oldObstacle);
}
}
}
function setupControls() {
const speedSlider = document.getElementById('speedSlider');
const heightSlider = document.getElementById('heightSlider');
const gaitSlider = document.getElementById('gaitSlider');
speedSlider.addEventListener('input', (e) => {
moveSpeed = parseFloat(e.target.value);
document.getElementById('speedValue').textContent = moveSpeed.toFixed(1);
});
heightSlider.addEventListener('input', (e) => {
legHeight = parseFloat(e.target.value);
document.getElementById('heightValue').textContent = legHeight.toFixed(1);
// Update leg lengths
creature.legs.forEach(leg => {
leg.upperLeg.scale.y = legHeight;
leg.lowerLeg.scale.y = legHeight;
leg.lowerLeg.position.y = -1.7 * legHeight;
leg.foot.position.y = -2.3 * legHeight;
});
});
gaitSlider.addEventListener('input', (e) => {
gaitSpeed = parseFloat(e.target.value);
document.getElementById('gaitValue').textContent = gaitSpeed.toFixed(1);
});
}
function togglePause() {
isPaused = !isPaused;
}
function resetCreature() {
creature.body.setTranslation({ x: 0, y: 2, z: 0 });
creature.body.setLinvel({ x: 0, y: 0, z: 0 });
creature.body.setAngvel({ x: 0, y: 0, z: 0 });
targetPosition.set(0, 0, 0);
creature.rotation.set(0, 0, 0);
creature.legPhase = [0, Math.PI, Math.PI, 0];
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
}
function updateCamera() {
// Camera follows creature
const creaturePos = creature.position;
const targetX = creaturePos.x - Math.sin(creature.rotation.y) * 10;
const targetZ = creaturePos.z - Math.cos(creature.rotation.y) * 10;
camera.position.x = THREE.MathUtils.lerp(camera.position.x, targetX, 0.05);
camera.position.z = THREE.MathUtils.lerp(camera.position.z, targetZ, 0.05);
camera.position.y = THREE.MathUtils.lerp(camera.position.y, creaturePos.y + 5, 0.05);
camera.lookAt(creaturePos.x, creaturePos.y + 1, creaturePos.z);
}
function updateFPS() {
frameCount++;
const currentTime = performance.now();
if (currentTime >= lastTime + 1000) {
const fps = Math.round((frameCount * 1000) / (currentTime - lastTime));
document.getElementById('fps').textContent = fps;
frameCount = 0;
lastTime = currentTime;
}
}
function animate() {
requestAnimationFrame(animate);
const deltaTime = clock.getDelta();
// Update physics
world.step();
// Update creature
updateCreature(deltaTime);
// Update camera
updateCamera();
// Update obstacles
obstacles.forEach(obstacle => {
const pos = obstacle.body.translation();
obstacle.position.set(pos.x, pos.y, pos.z);
obstacle.quaternion.copy(obstacle.body.rotation());
});
// Update FPS counter
updateFPS();
renderer.render(scene, camera);
}
// Start the application
init();
</script>
</body>
</html>