0
\$\begingroup\$

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);
    }   
}
}
\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

It is happening because you are translating every coordinates with/without reason. To overcome this problem you should just use some geometry or built-in unity methods which only cares about the target and follows the target in straight path.

Well, the easy solution for now is to use Vector3.MoveTowards.

Modify your update code as following,

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);
            transform.position = Vector3.MoveTowards (transform.position, targetTran, 0.1f);
        }   
    }
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .