Cerulean Boidtank

Boids is a steering algorithm written by Craig Reynolds in 1986, simulating animal flocking behavior. Boids are programmatic objects with three functions: separation, alignment, cohesion.

preventing collision
collective targeting
staying close

The light blue animated screen above is written in Processing, and run on the web through HTML5. The screen refreshes 30 times per second. With every refresh, each of the 150 triangular boids compares its location (x,y coordinate) and velocity (speed and direction) with the location and velocity of the closest boids in the flock. Using their three rules, each boid updates its vector and moves to a new location. Here is a simplified version of the code:

  1. Draw a screen 600x400 pixels, give it a blue background.
  2. Create a class for storing objects, call it a flock.
  3. Add 150 objects to this flock, call them boids.
  4. If the mouse is clicked, then add a new boid to the flock at the mouse's coordinates.
  5. Initialize the flock of boids as an array, so the boids can compare themselves to each other.
  6. Define the boid object, so that each boid can store its location, velocity, and acceleration as vectors.
  7. Render each boid as a triangle, oriented in the direction of velocity, four pixels wide and eight tall.
  8. Define the boid's three functions: separation checks for nearby boids and steers away; alignment checks where nearby boids are targeting and steers towards that goal; cohesion checks the location of nearby boids and steers towards them.
  9. Clear the screen, update steering vectors, and render boids. Repeat thirty times a second, infinitely.

Here is my version of the code, just slightly modified from the sample code found here. My boids have a lower maxspeed, and in the borders() function, they hit walls instead of wrapping around. To run this code and modify it for yourself: download Processing, copy/paste the code, and hit play.