Boids
A flock of starlings turns as one body, but no bird is in charge. Each one
only watches the few birds around it. In 1987 Craig Reynolds showed that three simple
steering rules, followed by every bird on its own, are enough to get that flocking. He
called his simulated birds "boids."
the three rules
Every bird looks at the others within its vision radius and adds up three
pushes:
separation: steer away from each nearby bird, harder the closer it is, so
birds don't collide.
cohesion: steer toward the average position of the birds it sees, so it
doesn't drift off alone.
alignment: steer toward the average velocity of the birds it sees, so
neighbors end up flying the same way.
Birds also turn back from the edges of the screen, and flee from your cursor or finger.
That's all of it. Nothing in the code knows what a flock is.
the colors
A bird's color comes from the direction it's flying. Birds heading the same way share a
color, so you can see alignment spread: a mixed crowd settles into patches of one hue as
each group agrees on a heading.
finding neighbors quickly
The obvious way to find a bird's neighbors is to check its distance to every other bird.
With a thousand birds that's a million checks per step. Instead the screen is cut into
square buckets the size of the vision radius, and each step every bird is filed into its
bucket. Anyone a bird can see must be in its own bucket or one of the eight around it, so
it only checks those, a small fraction of the flock instead of all of it.