Need support on my basic navmesh ai script to follow the player at a certain distance
I know this is kind of a noob question but I really need some quick help, I have this simple AI script that allows an object to follow the player on a navmesh, but for the life of me I cant figure out how to get the object to only follow me when I am in a certain distance of it, and when I am out of reach, the object will stop following the player. The javascript i have is below.
var target : Transform;
var navComponent : NavMeshAgent;
var anim : Animator;
function Start () {
target = GameObject.FindWithTag("Player").transform;
navComponent = this.transform.GetComponent(NavMeshAgent);
anim = GetComponent("Animator");
}
function Update () {
if(target) {
navComponent.SetDestination(target.position);
anim.SetFloat("speed",1);
}
}
Answer by Geometrical · Oct 09, 2016 at 11:48 PM
Here's some spoon feeding for you:
var target: Transform;
var navComponent: NavMeshAgent;
var anim: Animator;
var followDistance: float; // the distance in which to follow the player
function Start() {
target = GameObject.FindWithTag("Player").transform;
navComponent = this.transform.GetComponent(NavMeshAgent);
anim = GetComponent("Animator");
}
function Update() {
if (target) {
var distanceToTarget = Vector3.Distance(transform.position, target.transform.position);
if (distanceToTarget <= followDistance) {
navComponent.Resume();
navComponent.SetDestination(target.position);
anim.SetFloat("speed", 1);
} else {
navComponent.Stop();
//anim.SetFloat("speed", 0);
}
}
}
@Geometrical thank you for the reply and the script but i get an error telling me at lines 14,17: UCE0001: ';' expected. and tells me to insert one at the end, but there are already semicolins at the end of those lines, what could be wrong?
Updated the code, try again. Select my answer as the answer if it works.
@Geometrical thanks, it works now. I plan on learning basic scripting like this soon so I don't need to ask for help. $$anonymous$$uch appreciated.