Simulating Boids
Inspired by some videos I saw on YouTube, I decided to make my own boids simulation program in Scratch. Boids is the name of a technique by Craig Reynolds to simulate the grouping of animals, such as a flock of birds, or a school of fish.
In particular, I was impressed by how simple the algorithm was, yet how effective its results were, and I wanted to play around with it myself.
In the Boids algorithm, a "boid" is one of the creatures inside the simulated flock. It can see surrounding boids within a radius of itself. Reynolds proposed three behaviors for a boid, which have been named Separation, Alignment, and Cohesion:
- Separation: avoid colliding with nearby boids.
- Alignment: attempt to match the velocity of nearby boids.
- Cohesion: steer towards the average position of nearby boids.
These behaviors, or "forces" aren't applied one at at a time, they are applied together, with adjustable magnitudes, meaning the boid will move in a direction determined by a mix of new directions created by each force.
In some ways, my implementation differs from more standard implementations, because I didn't do terribly extensive reading on the technique beforehand or study an existing implementation. For instance, on top of those behaviors, I also regulate the speed of each boid, so the simulation doesn't slow down or speed up over time.
I have also added obstacle avoidance, which allows the boids to explore different stages without flying through everything. For it to work, each boid has 3 sensors, defined by costumes. Each sensor corresponds to a certain direction (forward, left, right). The costumes are very slightly asymmetrical, but it shouldn't make any noticeable difference. This doesn't work perfectly all the time, though, so sometimes you'll see a boid force itself through a wall.
All of this is done with vector math.
You can read more about boids here:
https://www.red3d.com/cwr/boids/