Need help keeping enemies at distance from player!!

having some trouble keeping enemies at a distance from player in combat. I can get the enemies to run towards the player to get within attack range, but when i move closer to the enemy i want them to run away to their range distance. Any help would be much appreciated :slight_smile:

    public Transform target;
    public float speed = 0.5f;
    private float minDistance = 4f;
    private float range;

void Start () {
        target = GameObject.FindWithTag("Player").transform;
    }

  void update() {
        range = Vector2.Distance(transform.position, target.position);

        if (range > minDistance)
        {
            transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
        }
}

Could you just use “Negative values of maxDistanceDelta” because that “pushes the vector away from target.” ? (Taken from Unity - Scripting API: Vector2.MoveTowards)

So if the Range < minDistance, just make that distance delta times -1

Ahh thankyou very much!! i feel dumb for having to ask this question now lol

Sound boarding off people is the life blood of programming.

2 Likes