- Home /
NavMesh problem it does not respond corectly
I have a GameObject Enemy which is supposed to chase the player all around the game board using its NavMeshComponent. The concept is: the enemy has a SphereCollider of radius 6 and everytime the player enters that collider, the enemy starts chasing him for as long as the player finds itself in the enemy's collider. Once the player exists the SphereCollider, the enemy enters an idle state and stays this way until the enemy detects the player again. I will provide you with the script for the enemy instance:
using UnityEngine; using System.Collections; using UnityEngine.UI; public class TrollMovement : MonoBehaviour {
private NavMeshAgent agent;
GameObject target;
public Image img;
public int healthEnemyPoints=100;
bool follow=false;
void Start ()
{
agent = GetComponent<NavMeshAgent> ();
target = GameObject.Find ("Player");
img.enabled = false;
agent.speed = 15f;
agent.acceleration = 50f;
agent.destination = target.transform.position;
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag ("Player"))
{
follow = true;
img.enabled = true;
}
if (other.CompareTag ("Bullet"))
healthEnemyPoints -= 1;
}
void OnTriggerExit(Collider other)
{
if (other.CompareTag ("Player")) {
Debug.Log ("A iesit playerul");
img.enabled = false;
follow = false;
agent.enabled=false;
}
}
void Update ()
{
if (healthEnemyPoints <= 0) {
agent.enabled=false;
Destroy (gameObject);
}
/*if (Input.GetKeyDown (KeyCode.Space))
//Destroy (this.gameObject);*/
if (follow == true) {
agent.enabled = true;
}
}
}
To clarify, the Image here is used just to show me whether the triggers are corectly triggered. My problem would be that the enemy, after one cicle of active-idle state, starts behaving strangely. Firstly, it doesn't start chasing the player immeadiately and morever, once it detects the player, it chases him only a fraction of move, after which the enemy enters its idle state.
I'm terribly sorry for my coding style, but I would like to know what could be changed about my code in order to achieve the perfect performance of my enemy. Should you have another idea of script, please post it!