Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question NavMesh Agent weird behavior

Discussion in 'Navigation' started by GreenDiggy, Mar 15, 2021.

  1. GreenDiggy

    GreenDiggy

    Joined:
    Jun 1, 2020
    Posts:
    1
    I have been trying for days to get this movement to work and I can't figure out the problem. I want the enemy to wander forward for a distance at the moment, but when I try to apply the transform.forward, instead of moving along the z-axis as it should, it starts drifting off in a backward diagonal direction.

    Code (CSharp):
    1. public class ZombiePathfinding : MonoBehaviour
    2. {
    3.     public Animator animator;
    4.     public NavMeshAgent agent;
    5.  
    6.     private Vector3 target;
    7.     private float timeLeft = 5.0f;
    8.  
    9.     void Awake()
    10.     {
    11.         agent = GetComponent<NavMeshAgent>();
    12.         animator = GetComponentInChildren<Animator>();
    13.     }
    14.     void Update()
    15.     {
    16.         timeLeft -= Time.deltaTime;
    17.  
    18.         if (timeLeft < 0)
    19.         {
    20.             agent.SetDestination(transform.forward);
    21.         }
    22.     }
    23. }
    Any ideas on what could be going wrong?
     
  2. batvink

    batvink

    Joined:
    Sep 26, 2019
    Posts:
    53
    Transform.forward is 0,0,1 with respect to the direction of the agent.
    So if you are in front of this global coordinate by more than 1 unit, when you set the destination it will try to find it's way backwards to 0,0,1.