Joe Wheater
Posted on November 22, 2017 by wheatsbeats on Demo, GPU, Shader, Unity

Unity GPU Flocking

Over the weekend I decided to look into creating some flocking behaviors computed on the GPU in Unity.

To start I implemented the three core principles: separation, alignment and cohesion of Boids flocking behaviors into a compute shader. On top of the three core principles I added two methods to attract and repel each Boid towards and away from a location. This added behavior allows for control over the flock as you attract and repel them to and from the mouses location. To visualize the Boids and flocking behaviors I used a technique called GPU Mesh Instantiating, details of this technique can be found on Unity’s documentation here.

Below is a video demonstrating this principles in action :

Edit – 20/05/2018

Recently I continued developing the concept further by turning the cubes meshes from the original example into a mesh of a fish. In order to progress I had to solve some issues with the previous example. The main issue was the Boids didn’t rotate to face the direction of travel. When visualizing the algorithm using cubes this limitation is not as noticeable as they are uniform in shape, however if I wanted to visualize a more realistic example such as birds or fish this would need to be solved. The solution involved calculating the rotation from current Boid position with the next Boid position and then passing that information to the final shader where it would be transformed from world local object space as a matrix calculation.

Another improvement that I made was using vertex displacement to deform the mesh of the fish to make look as though it is swimming. This was achieved by using the red channel in a separate texture input and painting a red to black gradient. The gradient describes the amount of displacement to apply to each vertex, red being the most displacement possible and black being no displacement at all.

Here is an example of the textures used to displace the body (left) and the fins (right) of the fish.

Below is a video of the improvements :


Leave a Reply