- Home /
Question by
Crispinator · Oct 10, 2013 at 08:54 PM ·
javascriptdistancetarget
How do I get an NPC to stop Following a player based on distance?
I have a wolf. The wolf follows the player because of the tag. For some reason, when I add the section of code about distance, the wolf doesn't move.
var target : Transform;
var moveSpeed = 3;
var rotationSpeed = 3;
var myTransform : Transform;
function Awake()
{
myTransform = transform;
}
function Update () {
var dist = Vector3.Distance(gameObject.Position, gameObject.FindWithTag("Player").Position);
if(dist < 10){
Debug.Log("Hit");
target = GameObject.FindWithTag("Player").transform;
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
myTransform.position += myTransform.forward * moveSpeed * Time.deltaTime;
}
}
Comment
Answer by robertbu · Oct 11, 2013 at 01:48 AM
If you'd left '#pragma strict' at the top of the file, the problem would have generated an error. Your problem is that 'Position' is not a member of a game object. The line should read:
var dist = Vector3.Distance(transform.position, GameObject.FindWithTag("Player").transform.position);
Note it would be more efficient to do the FindWithTag() once in Start() and cache the result (or better yet the transform of the result) rather than do it each frame.
Your answer
Follow this Question
Related Questions
Manipulate gameobjects, pick up & rotate 0 Answers
Error in distance coding 1 Answer
Simple code is not recognizing tag anymore. 0 Answers