- Home /
How To Make NPC Follow Player When In Range?
I am trying to make a hostile NPC follow and attack my player when the player is in range of the NPC. Currently, the NPC's with the following script attached start following my player the instant I start the game, even when they are very far away. I want to change that.
My script:
if(attack.rigidbody2D.transform.position.y > (rigidbody2D.transform.position.y + distance)){
rigidbody2D.transform.position += Vector3.up * speed * Time.deltaTime;
}
if(attack.rigidbody2D.transform.position.y < (rigidbody2D.transform.position.y - distance)){
rigidbody2D.transform.position += Vector3.down * speed * Time.deltaTime;
}
if(attack.rigidbody2D.transform.position.x > (rigidbody2D.transform.position.x + distance)){
rigidbody2D.transform.position += Vector3.right * speed * Time.deltaTime;
}
if(attack.rigidbody2D.transform.position.x < (rigidbody2D.transform.position.x - distance)){
rigidbody2D.transform.position += Vector3.left * speed * Time.deltaTime;
}
Comment
Answer by smallbit · Mar 02, 2015 at 02:26 PM
http://docs.unity3d.com/ScriptReference/Vector3-sqrMagnitude.html
This is better version of distance. Check this on update, comparing position of enemy and player, when its lover than attacking distance (like in example need to be squared, since this is square magnitude), and than perform attack action.
Your answer
![](https://koobas.hobune.stream/wayback/20220613184729im_/https://answers.unity.com/themes/thub/images/avi.jpg)