If you’ve been following me on YouTube or taken any of my Udemy courses you’ll know I am fascinated by the flocking algorithm. Usually I create a multitude of fish tank scenes with it including this augmented reality one I posted to YouTube for object recognition “How to use Object Recognition” with Wikitude.
Converting the algorithm for ground dwelling creatures with gravity applied is straight forward if you know what you are doing. Recently I was asked how to do this for sheep.
Assuming you’ve followed my flocking tutorials for fish such as Flocking Fish in a Box with Speed Adjustment Slider.
You can create a flock of sheep by giving your models a rigid body and colliders. In the above example, the sheep are situated on an undulating terrain. To make these sheep I simply took the existing fish flocking code I had and replaced the fish models with sheep. This created a very elegant space fairing species of Artiodactyla.
Nothing too special about that. However to get them to gravitate towards a ground, I had to add first of all a terrain, to which I added a few hills and a grass texture and then to the sheep model added a rigid body and four sphere colliders, one for each leg like this:
Note that gravity is turned on and the Z rotation is frozen to stop the sheep tipping over in the rigid body. Each sphere is added around the sheep legs. I tried this with a single collider around the whole sheep and found that I couldn’t keep the sheep grounded correctly. You might find you get better results doing it another way. But this worked for me.
With the sheep forced to the ground, the next change that needed to be made was in the flocking script itself. The direction the flocked object is required to turn towards is in 3D space. This works for fish (or space fairing sheep) but not for ground dwellers.
So the quick way to achieve this was to 0 the Y rotation for any direction changes in the script. This occurs in 2 places. Essentially, after the direction in the flock is calculated I simply set the direction’ Y to zero, like this:
Vector3 direction = (vcentre + vavoid) – transform.position;
direction.y = 0;
When all is said and done, you end up with flocking sheep!Download Project File
If you are interested in learning more AI techniques used in games, be sure to check out my AI course on Udemy.