- Home /
NavMesh Agent question
I have been reading about Navmesh Agent and i decided that this is the best place to start making the Enemy AI of my FPS. Navmesh allow an object to follow another object, avoiding stactic objects, turning smoothly towards it's target, turning around when blocked, etc...
It's basically a FOLLOW AI. But i wanted to know if i can customize it to also do the following:
If the target is behind a house for example, then the enemy will NOT follow him, but instead patrol in the house's area surroudings. And if the enemy is ........... meters away from the player, then stop and follow him again if the player is not .......... meters from the enemy.
A friend helped me making a script which you attach to a gameobject with a navmesh agent, and then you specify the gameobject's target. If the answer for this is by using script, here it is:
using UnityEngine;
using System.Collections;
public class NavFollow : MonoBehaviour {
public Transform target; //Usually the player
void Start () {
StartCoroutine(FollowEnemyCoordinates());
}
void Update () {
}
//This will set the target position for the NavmeshAgent every so seconds so we don't waste performance
IEnumerator FollowEnemyCoordinates() {
while (true)
{
//This will set the target coordinates
GetComponent<NavMeshAgent>().SetDestination(target.position);
//This will wait for 1 second before looping
yield return new WaitForSeconds(1);
}
}
}
Could someone experienced in NavMesh or at least someone that know how to make this help me? This would help a lot.
Answer by Cynikal · Nov 03, 2016 at 11:22 PM
So, Let's break this down.
If the player is behind an object, do not follow
If the enemy and player are so far away, stop following.
For #1: Use a Raycast always pointing to the player from the enemy. -- If the Raycast hits the player directly, he has light of sight. Follow. If it hits anything other than the player, line of sight is lost. Stop following.
For #2: Use Vector3.Distance(Player Position, Enemy Position).
if (Vector3.Distance(Player.Position, Enemy.Position) >= MaxFollowDistance) StopFollowing();
To stop an agent, simple use .Stop(); on the nav mesh agent.
Further more, for optimization:
You shouldn't keep referencing your NavMeshAgent via GetComponent. It's a "heavy" feature.
What you should do is:
public class of whatever {
NavMeshAgent nma;
void Start()
{
nma = GetComponent<NavMeshAgent>();
}
}
Then instead of hitting your
//Instead of: GetComponent<NavMeshAgent>().SetDestination(target.position);
//Use:
nma.SetDestination(target.position);