16 August 2020
These simulations are being rendered using individual HTML elements with CSS translations, and they're very easy to include in a web page, just include the script and create a boundary for the boids to work in. They'll even follow your mouse if you move it around near them. Lets take a look at what's going on behind the scenes to create this flocking behaviour:
Bounding
Each boid starts in a random place, with a random velocity. In this example with just one boid, it will just carry on with the same velocity until it gets close to the edge of the region it's in. At this point it's velocity will be nudged in the opposite direction in proportion to how close it is to the boundary, stopping it from just flying off the screen at the first opportunity.
Attraction
Each boid is setup with a maximum visual range, and each boid can only see other boids within this visual range. Put another way, if you imagine a circle drawn round each boid, it can only see other boids within its circle. This part is by far the most computationaly intensive as for each boid, we much calculate the distance to every other boid in order to know which other boids are within it's vision.
Boring computer science interjection Imagine a boid with 3 other boids around it. To calculate whether any of those are within it's vision, we have 3 distance measurements to take. Then when we do the same with each of those other boids, we also have to do 3 measurements. So the number of calculations is 3x3, aka 3². This means the simulation has a big-O notation of N², so the time it takes to simulate increases with the square of the number of boids.
With two boids present you can see that generally one ends up following behind the other. This is mainly because the simulation is setup so that a boid can't see behind itself. So from the perspective of the boid infront, it doesn't have anything to follow, and will just continue straight while the others will follow along behind.