Lawrence William Trigg Lawrence William Trigg - 2 months ago 7
C# Question

NPC will not stop at a certain distance of the player

I have a NPC which follows my player but I cant get it to stop when it is at a certain distance from the player. This has been frustrating me all night as there is nothing on the web for doing this.

They collide and hit each other!

Here is my code for moving the NPC:

using UnityEngine;
using System.Collections;

public class AI : MonoBehaviour {
public Transform target;
public int moveSpeed = 5;
public int rotationSpeed = 2;
public Transform myTransform;

void Awake ()
{
myTransform = transform;
}

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

void Update ()
{
myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * moveSpeed * Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;

}
}

Answer

You need to only apply the movement code if it's to far away. If it's close enough then apply no movement code. ie update should be:

Vector3 Distance = target.position - myTransform.position;
if(Distance.sqrMagnitude>minDistance*minDistance)
{
    myTransform.rotation = Quaternion.Slerp (myTransform.rotation, Quaternion.LookRotation (target.position - myTransform.position), rotationSpeed * moveSpeed * Time.deltaTime);
    myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}