Ondrej Paska Blog

Swarm of Fireflies in Unity

Advertisements

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:

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.

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.

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.

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.

Advertisements

Advertisements