- Home /
NavMeshAgent does not move to an updated position
Hi
I've got the following script asking a navMeshAgent to move to a position dynamically. What's happening is the Agent moves to the starting location of the Player gameObject and doesn't move or rotate after that, even though the player object has moved.
public class EnemyMover : MonoBehaviour
{
public GameObject bullet;
public NavMeshAgent agent;
public Transform target;
public float fireRate;
private float nextFire;
public GameObject Player;
public float fireRange;
Vector3 LastKnownPos;
int takeDamage;
public int EnemyDamage;
public int HP;
public Transform shotSpawn1;
public Transform shotSpawn2;
Transform shotActive;
public Transform eye;
public float range;
public LayerMask playerLayer;
// Start is called before the first frame update
void Start()
{
fireRange = 6f;
takeDamage = 2;
HP = 6;
shotActive = shotSpawn1;
}
void Update()
{
//Debug.DrawRay(eye.transform.position, transform.TransformDirection(Vector3.forward)*range);
//RaycastHit sight;
//if (Physics.Raycast(eye.transform.position, transform.TransformDirection(Vector3.forward), out sight, range, playerLayer))
//{
CustomEvent.Trigger(gameObject, "alert");
agent.updateRotation = true;
agent.SetDestination(Player.transform.position);
agent.stoppingDistance = fireRange;
//Vector3 lastKnownPos = Player.transform.position;
// }
}
At least stopping distance is pretty long.. if the agent is within the 6 units it will not move towards the player.. Also set the updateRotation and stoppingDistance in the Start(). They don't need to be set in every frame
Thank you @CodesCove for the heads up :) I've made the changes you recommended. On a side note, I have tried to move the unit without a stopping distance also, but the Nav$$anonymous$$eshAgent only moves to the player.transform.position when I hit play and stops moving after that. Should I try this with the .destination parameter instead?
Answer by HemK · Sep 22, 2020 at 05:05 AM
Made a silly mistake. The NavMeshAgent I wanted to follow was a child object of the target. The Target was at 0,0,0 and the agent in the script was moving to that location, while the intended target was moving about. I simply assigned the child object as the target in the Inspector and problem solved.
I'm not deleting this post in case somebody else makes this noob mistake and wants to save themselves the public embarrassment.
Your answer
Follow this Question
Related Questions
Runaway AI 1 Answer
No player is colliding with enemy even with capsule collider !!! Please me help me. 0 Answers
NavMeshAgent Not Working? 1 Answer
A way to check if an off mesh link is nearby? 0 Answers
Problem with AI and pathfinding. 2 Answers