Three.js Predator–Prey Ecosystem Simulation

Agent-based ecosystem in Three.js where rabbits graze regrowing grass and foxes hunt them, producing Lotka–Volterra-style population cycles shown on a live chart.

Key topics: three.js ecosystem, predator prey, lotka volterra, agent based simulation, population dynamics, boids

What this code does

- Energy Budget: animals spend energy over time, gain it by eating, reproduce above a threshold and die at zero.
- Grass Field: a 40×40 grid regrows logistically and is drawn as instanced tiles shading from lush green to bare dirt.
- Behaviours: rabbits wander and flee foxes they can see, and foxes steer toward the nearest rabbit within vision.
- Spatial Buckets: agents are hashed into grid cells so nearest-neighbour searches stay fast with over 1,000 animals.
- Population Cycles: prey booms are followed by predator booms and crashes, the classic Lotka–Volterra lag.
- Controls: sim speed, grass regrowth, birth thresholds, vision radii and initial populations.

Continue Learning

JavaScript Implementation

ES6+
// Predator–prey agents: rabbits graze, foxes hunt, both reproduce when well fed
const rabbits = Array.from({ length: 200 }, () => ({ x: Math.random() * 40 - 20, z: Math.random() * 40 - 20, e: 4, h: 0 }))
const foxes = Array.from({ length: 15 }, () => ({ x: Math.random() * 40 - 20, z: Math.random() * 40 - 20, e: 10, h: 0 }))
const move = (a, speed, dt) => {
  a.h += (Math.random() - 0.5) * 2 * dt
  a.x = Math.max(-20, Math.min(20, a.x + Math.cos(a.h) * speed * dt))
  a.z = Math.max(-20, Math.min(20, a.z + Math.sin(a.h) * speed * dt))
}

function step (dt) {
  rabbits.forEach(r => { move(r, 1.6, dt); r.e += dt * 0.3 }) // grazing
  foxes.forEach(f => {
    move(f, 2.2, dt)
    f.e -= dt * 0.6
    const prey = rabbits.find(r => !r.dead && (r.x - f.x) ** 2 + (r.z - f.z) ** 2 < 0.6)
    if (prey) { prey.dead = true; f.e += 4 }
  })
  const born = (list, threshold) => list.filter(a => a.e > threshold).map(a => { a.e /= 2; return { ...a } })
  rabbits.push(...born(rabbits, 6))
  foxes.push(...born(foxes, 14))
  for (const list of [rabbits, foxes]) {
    for (let i = list.length - 1; i >= 0; i--) if (list[i].dead || list[i].e <= 0) list.splice(i, 1)
  }
}

// draw rabbits/foxes as InstancedMesh, updating matrices from (x, z) every frame