Simplified Flock Algorithm for glow worm’s AI

Hi! Today I want to show You how simply add something to make your scene more interesting. It is very simple AI algorithm driving a light (I have used universar rendering pipie line to add 2d lights)

I have used light because i wanted to experiment with this feature but it can be replaced with transparent texture. It will be more efficient, lights consume lot of caluation power.

I have created C# component:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GlowWorm : MonoBehaviour
    public Transform target;
    public float speed = 1;
    public float randomize = 1;
    // Start is called before the first frame update
    void Start()

    // Update is called once per frame
    void Update()
        float step = speed * Time.deltaTime; // Vector3.Distance(target.position, transform.position); ; // calculate distance to move
        transform.position = Vector3.MoveTowards(transform.position, target.position, step);
        transform.position = new Vector3(transform.position.x+Random.Range(-randomize, randomize), transform.position.y + Random.Range(-randomize, randomize), transform.position.z);

As You can see this component will drive game object toward the target with “speed” velocity. Additionaly this movement will be disturbed with random fluctuation with “randomize” intensity

You can place this component on light objects. Set target to “player” object. You can also chain lights that they can have differetnt target an will follow each other.

This script can be extended. Eg When minimal distance threshold i exceeded then speed become negative if maximal distance threshold is exceeded then speed becomes postive again.

Leave a Reply

Your email address will not be published. Required fields are marked *