I currently have a script which (in 2D space) tells my enemy GameObject to chase after my target (the player). I want it so when the enemy gets too close or when the player moves towards it, it dodges out of the way.
In my code I effectively just said the opposite of the ‘chase’ code (so when it gets too close, move in the opposite direction of the players location).
When I test it, the enemies:
- move towards the player normally
(which is fine) - as soon as they hit minimum distance they immediately move back to their original location
- if I DO manage to move my character on top of one it flickers constantly
Any ideas? Is there another function that will allow for just moving in a random direction AWAY from the target when I’m within a certain range?
Thanks guys!
using UnityEngine;
using System.Collections;
public class GuardianKnightMeleeController : MonoBehaviour
{
public Transform target;
public float speed = 5f;
private float minDistance = 3f;
private float range;
void Update()
{
range = Vector2.Distance(transform.position, target.position);
if (range > minDistance)
{
transform.position = Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
if (range < minDistance)
{
transform.position = -Vector2.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
}
}
}