So I recently designed an enemy that will follow the player when he comes within a certain distance of the object. However, there are times when the player comes in range, only for the "follower" enemy to seemingly reverse before following, or almost kind of circle the player on the way towards him.
I can't quite put my finger on why this is happening, so I have attached my code. I hope someone can give me some advice on how to improve this:
public class Follower : MonoBehaviour
{
// spawn position and other info of Follower
private Vector3 pos1 = new Vector3(-7f, 0.5f, -7f);
public float speed = 1.0f;
public int Range;
public GameObject target;
private Vector3 targetTran;
private Vector3 diffVec;
private float diffMag;
void Awake()
{
transform.position = pos1;
sourceCollFol = GetComponent<AudioSource>();
}
void Start ()
{
target = GameObject.FindWithTag("Player");
targetTran = target.transform.position;
}
void Update ()
{
pos1 = transform.position;
targetTran = target.transform.position;
diffVec = (targetTran - pos1);
diffMag = diffVec.sqrMagnitude;
// check for range between Player and Follower Enemy
if ( diffMag < Range)
{
transform.LookAt(targetTran);
diffVec.Normalize();
transform.Translate(diffVec.x * speed * Time.deltaTime, 0f, diffVec.z * speed * Time.deltaTime);
}
}
}