Swarm of Fireflies in Unity

I’d like to show you how to code the movement of an organic looking swarm of flies in Unity.

The result looks like this:

roj1

Let’s start simple. We can make one fly move in a circle. First we need to define the Radius and Speed, then we make use of the Sine and Cosine functions (check here if you need a refresher).

private float t;
public float Radius;
public float Speed;
// Update is called once per frame
void Update()
{
    t += Time.deltaTime;
    transform.position = new Vector3(
       Radius * Mathf.Cos(t*Speed), 
       Radius * Mathf.Sin(t*Speed),
       0);

The result is very regular circular movement.

circle

If you try putting a different radius for X then for Y, you will notice the circle becomes an ellipse.

What if we kept the radius for X steady and changed the radius for Y with an interesting periodic function?

First I used the great Desmos  graphics calculator to play around with different functions, until I found one that looks natural.

image (7)

Plugging in the formula for radius Y  as a fraction of Radius:

var radiusY = Radius *
                      (0.5f + 0.5f * (
                           Mathf.Sin(t * 0.3f) +
                           0.3 * Mathf.Sin(2 * t + 0.8f) +
                           0.26 * Mathf.Sin(3 * t + 0.8f)));
        
transform.position = new Vector3(Radius*Mathf.Cos(t*Speed), radiusY*Mathf.Sin(t*Speed), 0);

 

and the result (with the path traced with a gizmo) looks very natural to me.

single

The rest is just spawning more flies and make their radius and speed random. Also negative speed can make some of them fly in the other direction.

ten

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s