Saltar al contenido
← Volver a proyectos

Threejs Procedural Spider

A self-stabilizing procedural spider you can walk, climb, and leap across any terrain. Analytic IK legs, a flexible articulated body, and jumps that latch onto walls. Built with Three.js.

#🕷️ Procedural Spider

#Play the live demo · by @majidmanzarpour

A self-stabilizing procedural spider you can walk over any terrain. Eight legs solved with closed-form inverse kinematics, a gait that improvises its own footfalls, and a body that leans into slopes, walls, and overhangs — with no animation clips, no skeleton rig, and no physics engine. Just math, every frame. Built with Three.js.

Procedural Spider walking across rocky terrain

Drag the sliders, drive it around, watch the legs find their own footing. It's strangely calming.


#✨ Features

  • Analytic IK legs — each leg is solved with a two-bone closed-form solver (hip → knee → foot). No baked animation, no IK iterations to converge: one formula, exact, every frame.
  • Improvised gait — feet are planted in the world, not on the body. When the body outruns a foot, that leg lifts, arcs to a fresh foothold, and plants. Step timing is an alternating-gait state machine, so the walk re-times itself naturally as you speed up, slow down, or turn.
  • Terrain that's a function, not a mesh — the ground is a closed-form height field, so the spider can sample the exact height and normal at any point. That's what makes foot placement and body alignment rock-solid.
  • Climbs walls & overhangs — the body's up-vector blends toward the surface normal under it, so the spider tilts onto inclines and clings to steep faces instead of clipping or sliding.
  • A body that bends — two segments (cephalothorax + abdomen) joined at a flexible pedicel, so the abdomen folds at the waist: it hangs down on a wall, droops over a crest, and sags under its own weight. The spider flexes like a real spider, not a rigid blob. (Toggle: BODY FLEX.)
  • Knee-swivel collision avoidance — each leg searches a fan of knee orientations and picks the one that keeps the limb out of the ground and obstacles (tunable live).
  • Live tuning panel — speed, ride height, step height, gait rate, turn rate, stride, and the knee-swivel search, all adjustable while it walks.
  • Tiny & dependency-light — ~1,200 lines across 8 modules, with three as the only runtime dependency. Runs at hundreds of FPS.
  • Desktop & touch — WASD + mouse, or an on-screen joystick on phones/tablets.

#🎮 Controls

Action Desktop Touch
Move W A S D / arrow keys left joystick
Look drag the mouse right-side drag
Zoom scroll wheel
Boost hold Shift BOOST button
Reset R or the RESET button RESET button

The HUD (top-right) shows live FPS, speed, and the surface grade the spider is on (FLATINCLINEWALLOVERHANG).


#🚀 Quick start

npm install
npm run dev        # http://localhost:5173

Build a static bundle (drop dist/ on any static host — GitHub Pages, itch.io, a plain folder):

npm run build
npm run preview    # serve the production build locally

Requires Node 18+.


#🧠 How it works

The spider never plays an animation. Each frame it re-derives its entire pose from the world:

  1. Input → intent. Keyboard/joystick become a desired move direction and speed.
  2. Body controller. The body turns toward the intent, advances across the terrain, and holds a target ride height above the support plane formed by its planted feet (with BODY CONFORM), tilting its up-vector to match — so it leans on slopes, climbs onto steps/ledges, clings to walls, and never sinks into rising ground.
  3. Gait state machine. Eight legs share an alternating-tetrapod-style timing wheel. A foot stays planted in world space while the body moves over it; once the body stretches a leg past its stride threshold, that leg enters a step — lift, arc over stepH, and land on a new foothold.
  4. Foothold search. New footholds are sampled from the analytic terrain height and collider clearance, so feet land on real geometry — including vertical and inverted surfaces.
  5. Two-bone IK. Given the hip position, the foot target, and the femur/tibia lengths, the knee angle is solved in closed form (twoBoneKnee). A short knee-swivel search rotates the knee plane to the orientation that best avoids ground/obstacle penetration.
  6. Camera. A third-person follow camera trails the body and pulls in when geometry would clip it.

Everything is analytic — the terrain is a formula, the IK is a formula, collisions are distance functions. No physics solver, no rig, no animation data.

#Project structure

procedural-spider/
├── index.html              # canvas + HUD + tuning-panel markup
├── src/
│   ├── main.js             # bootstrap: renderer, scene, camera, tuning panel, render loop
│   ├── core/
│   │   ├── dynamics.js      # math layer: vectors, easing, the two-bone IK solver, helpers
│   │   └── Input.js         # keyboard + touch-joystick → { ix, iy, sprint, camYaw }
│   ├── world/
│   │   ├── terrain.js       # closed-form terrain height + exact normals
│   │   ├── collision.js     # analytic colliders (spheres/boxes), raycast, clearance
│   │   └── World.js         # scene build: lights, sky, terrain mesh, obstacles, dust
│   ├── spider/
│   │   └── Spider.js        # the creature: body controller, gait, legs, IK, foot probing
│   ├── camera/
│   │   └── SpiderCamera.js  # collision-aware third-person follow camera
│   └── ui/
│       └── styles.css       # HUD, tuning panel, and touch-control styling
└── docs/preview.jpg

Spider.js carries a few additive "game hooks" (an airborne/tether swing mode and some status fields) that are inert in this sandbox — they're kept verbatim from the game this was extracted from, so the locomotion code is exactly the battle-tested original.


#🎛️ Tuning panel

Open the TUNING panel (top-left) and adjust the spider while it walks.

#Experiment toggles (A/B switches at the top of the panel)

Toggle What it compares
IK SOLVER DECOMPOSED (default) ↔ ANALYTIC. The decomposed solver (Kiaran Ritchie, 2026) splits each leg into chain length (solved in the limb's rest frame) and chain direction (one aim rotation about the hip). The foot lands in the same place either way; the knee bend becomes base-driven, like a real hip socket. Flip it and watch the knees.
BODY CONFORM ONOFF. ON, the torso tilts to the support plane formed by the planted feet so it leans onto slopes and steps instead of staying rigidly level. OFF reverts to the lightly-sampled original tilt.
BODY FLEX ONOFF. The body is two segments — a cephalothorax and an abdomen — joined at a flexible pedicel (waist). With it ON the abdomen folds at the waist: it hangs down when the front rears up onto a wall, droops over a crest, and sags slightly under its own weight — so the spider bends like a real spider instead of a rigid blob. OFF locks the abdomen straight. Climb a wall and watch the abdomen hang.

#Sliders

Knob What it does
Speed base walk speed
Ride height how high the body floats above the surface
Step height how high feet arc during a step
Gait rate base stepping frequency
Turn rate how fast the body yaws toward your input
Stride maximum foot reach before a leg must re-step
Knee swivel range angular span of the knee-orientation search
Knee swivel samples how many orientations to test (quality vs. cost)

Push Ride height down and Step height up for a skittery bug; raise stride and slow the gait for a lumbering tarantula.


#🔌 Headless API

For experiments and automated testing, the running app exposes a small global:

// step the simulation deterministically (handy when the tab is hidden / for screenshots & tests)
window.GOSSAMER.drive(steps = 60, ix = 0, iy = 1, sprint = false);

// live handles
window.GOSSAMER.spider;     // the Spider instance — read pos/up/speed, tweak knobs
window.GOSSAMER.world;      // the World
window.GOSSAMER.renderer;   // the Three.js WebGLRenderer

// renderer + pose snapshot
window.__THREE_GAME_DIAGNOSTICS__.state;   // { fps, spider:{pos,up,speed}, drawCalls, triangles }

drive() advances the spider at a fixed 1/60 timestep — useful because requestAnimationFrame pauses in background tabs.


#🛠️ Built with

No game engine, no physics library, no asset pipeline.


#📄 License

MIT © 2026 Majid Manzarpour.

Nueva versión disponible.