I've made myself a swarm

"So you've made yourself a swarm," you say. "But what's a swarm?" A swarm is an algorithm for producing natural-looking movement in large swarms of creatures. Another similar algorithm to use in similar situations is Craig Reynold's flocking algorithm. But the flocking algorithm is computationally expensive, so a swarm is a better alternative if you don't need accuracy, but a convincing organic movement of hundreds of creatures. The swarm I've made can easily run smoothly with 500 creatures.

The creatures can both run on the ground and fly, and you can include animations. When you zoom in you can see that the spiders's legs are moving and it's not decreasing the performance. If the creatures reach an obstacle they can climb (or fly a little higher), and when they reach the end of the obstacle they fall down. The climbing part is not yet that great because sometimes they will climb up but not always with the correct angle. But that's a later problem! They can also reach obstacles that can't be climbed and in that case they just turn around 180 degrees.

The creatures are running towards you, and when they reach you they slow down and begin to circle your position while trying to attack you.

It's also super-easy to reverse the roles: they hunter becomes the hunted. With a single button you can make it so the creatures disperse and run away from you.

They will also run away if they are injured, like if they touch a flame, and then die after a few seconds.

So what's the secret. First of all I got the idea from the article "Simple Swarms as an Alternative to Flocking" by Tom Scutt. You can find it in the book AI Game Programming Wisdom. But the basic idea is simple: use randomness:
  • The creatures have random top speed, which is how they spread out
  • The creatures have each a different random turn speed they can turn with
  • The creatures are using more randomness make their paths less straight and more natural-looking

Looks interesting? You can test it here: Swarm Algorithm.