Archive

Archive for May, 2014

Flocking

Expressing behaviors of artificial creatures is an interesting field. Sometimes complex behaviors can emerge from simple rules which I find exciting. A bit like the complex fractal patterns that can emerge from simple formulas that are repeatedly applied. One example of such a behavior is flocking:

Flocking behavior is the behavior exhibited when a group of birds, called a flock, are foraging or in flight. There are parallels with the shoaling behavior of fish, the swarming behavior of insects, and herd behavior of land animals.

[wikipedia]

Flocking can be expressed using three simple rules (more or less copied from Wikipedia):

  • Separation – apply a repulsive force to the closest neighbors to avoid singularities
  • Alignment – the direction of an individual is adjusted towards the “mean value” of its neighbors
  • Cohesion – the direction of an individual is adjusted towards the mass center of its neighbors

The details are explained in this article; http://gamedevelopment.tutsplus.com/tutorials/the-three-simple-rules-of-flocking-behaviors-alignment-cohesion-and-separation–gamedev-3444.

I more or less just ported the code to javascript and played around with the flocking parameters. One thing that I changed was that I only apply the separation rule to a more restricted neighborhood than the original article.

My code can be found here: https://bitbucket.org/d95danb/flocking.js. I wrote and debugged the code directly from within chrome. Just loaded the initial page and pressed F12. Simple but actually rather pleasant. Breakpoints, variable watch, auto complete, coloring – most things are there those days. Life is good.

Made a small video of the result (the screen capturing did some evil to the frame rate…).

flocking.js demo
Categories: Uncategorized