This spring I was working on a “ocean themed” site taking the user on a journey to the great depths of the North Sea. And of course, in every ocean there needs to be
fish happily swimming in flocks. So I started doing some research into flocking, and with some experience from creating particle systems, the first prototype was done in in a day.
The basics of flocking is that one fish tries to find a buddy to follow, one that it can see in a sector relative to it’s swimming direction. Once a buddy is found, it tries to follow as best it can, limited by its max speed among other properties.
To see who a fish is following, hold the shift-button on your keyboard. Red lines will point out the leader, also green lines will display the “negative force field” that the mouse cursor is to the fishes. The are just really scared of the cursor, trying to avoid it the best they can.
Feel free to peek into the code using the link below, there are some comments that should explain the basics. I wrote the code from scratch with a JS “class” for a Fish, making it easy to instantiate a thousand of them with the “new” operator. The particle system is drawn on a canvas, drawing the fish from a bitmap with correct rotation and position from its “particle” properties.
Go ahead, visit CodePen: http://codepen.io/gadgetgnome/pen/Apnkv