To implement the flocking behavior, I employed Craig’s Reynolds algorithm to implement the behavior of flock (Reynolds refers to them as boids). This consists of 3 basic rules:
a. Separation : The purpose of this rule is to keep the boids from colliding with each other. A minimum distance has to be maintained between them and if 2 boids come closer than the minimum distance, move the other boid away. This is done by subtracting a vector from the displacement of the two boids.
b. Cohesion : This rule makes the boids move towards it’s center of mass. I modified this rule by moving the center of mass to different locations. This gives the illusion that the flock is travelling across locations (i.e. herd following a leader). The center of mass changes every few seconds. I divide it by 100 to move the boid 1% towards the center every frame.
c. Alignment : We calculate the average of the boids and add a small portion to the current boid’s velocity.
All these rules are added to the the velocity of a boid. I also have made further tweaks to the algorithms. A function named LimitFlockVelocity has been employed to keep the velocity under a given value. Additionally, I am not calling all the rules every frame, rather I am calling it after a given amount of time (in my case 1 second and 0.5 seconds). This gives it a better effect and the velocities don’t change very quickly.
Dispersion: When you go near the flock, each element of the flock disperses away and returns only after you have left that particular area. To implement this I am calculating a perpendicular vector direction to the movement vector of each element of the flock. Now because there can be infinite perpendicular vectors to a given vector (as its a 3-variable equation), I set the value of two variables as 0 or 1 and calculate the third variable. I am also adding an element of randomness in deciding which two vectors will be pre-calculated and which will post-calculated. This gives an effect that all the elements of the flock are going in different directions.
References:
https://gamedevelopment.tutsplus.com/tutorials/3-simple-rules-of-flocking-behaviors-alignment-cohesion-and-separation–gamedev-3444
https://en.wikipedia.org/wiki/Boids
http://www.vergenet.net/~conrad/boids/pseudocode.html