- Home /
NavMeshAgent track Player when in Range?
Hello,
So I know absolutely nothing about coding and I need a simple Enemy Script where they just walk around randomly but when the player is close AKA in range, it moves towards them till the player exits their range and goes back to walking around. I'd really like to have code that I can copy and paste into unity.
Thank you for any help!
Use Physics.OverlapSphere
unity official documentation is available https://docs.unity3d.com/ScriptReference/Physics.OverlapSphere.html
write code yourself i just share the link of how you can check whether player is in range.
Answer by path14 · May 04, 2017 at 07:31 AM
You'll have to learn some coding to make a decent game (or whatever you want to do with it). I can point you in the right direction. Copy and pasting won't get you anywhere.
Attach a Nav Mesh Agent to the Enemy. Have it disabled.
Call the Nav Mesh Agent in a script attached to the Enemy with Vector3 Distance.
Something like this: (Javascript)
public var player : Transform;
function Awake () {
player = GameObject.FindGameObjectWithTag ("Player").transform;
nav = GetComponent (UnityEngine.AI.NavMeshAgent);
}
function Update() {
var distance = Vector3.Distance(player.position, transform.position);
if(distance <= 30) {
nav.enabled = true;
nav.SetDestination (player.position);
}
else {
this.nav.enabled = false;
}
}
I don't have the code for random enemy movement, but that's quite easy to write.
There are plenty of tutorials that Unity provides, which can help you. Please take the time to learn. It will pay off in the long run.
Answer by saadnation55 · Jul 07, 2020 at 05:59 PM
well this might solve your problem
public class Follow : MonoBehaviour { // Start is called before the first frame update
public List<GameObject> waypoint = new List<GameObject> ();
NavMeshAgent nav;
int index = 0;
int length;
bool range = false;
void Start () {
nav = GetComponent<NavMeshAgent> ();
length = waypoint.Count;
nav.SetDestination (waypoint[index].transform.position);
}
// Update is called once per frame
void Update () {
Collider[] colliders = Physics.OverlapSphere (transform.position, 10);
for (int i = 0; i < colliders.Length; i++) {
if (colliders[i].gameObject.name == "player") {
Debug.Log ("0");
range = true;
nav.SetDestination (colliders[i].gameObject.transform.position);
break;
} else
range=false;
}
if(range==true) return; if (nav.remainingDistance <= nav.stoppingDistance) { if (index >= length - 1) index = 0; else index++; nav.SetDestination (waypoint[index].transform.position); }
}
}
Your answer
Follow this Question
Related Questions
Runaway AI 1 Answer
Enemy's NavMesh not working 2 Answers
NavMesh flee. Ai flee from player. 4 Answers
NavMeshAgent does not follow player 0 Answers