Search Unity

navmeshagent.remainingdistance is wrong

Discussion in 'Scripting' started by Angela_, Aug 22, 2014.

  1. Angela_

    Angela_

    Joined:
    Feb 24, 2014
    Posts:
    9
    Hello there,
    I want to reload my level when remaining distance less then 1.
    But sometimes when my enemy is still far from the target, the remaining distance becomes 0.
    So is there a way to solve this problem ?

    Thanks
     
  2. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
    Yes... Show your code! :)
    (At least how do you calculate distance)
     
  3. Angela_

    Angela_

    Joined:
    Feb 24, 2014
    Posts:
    9
    This is my code

    public Transform target;
    private NavMeshAgent navMeshAgent;
    public float distanse;

    void Update ()
    {

    navMeshAgent = GetComponent <NavMeshAgent> ();
    navMeshAgent.destination = target.position;
    distanse = navMeshAgent.remainingDistance;

    if (distanse<=1)
    Debug.Log("Reload Level");
    }
     
  4. Fraconte

    Fraconte

    Joined:
    Dec 6, 2013
    Posts:
    327
    I never used navMeshAgent before but as fas as I can understand everytime you set destination a new path would be recalculated and that could requires more than one frame. So remainingDistance can sometime be undefined (incorrect?).
    Besides doing initialisation and setting path only when needed (possibly not every frame), you can try this:
    Code (CSharp):
    1.  
    2. if (distanse<=1 && !navMeshAgent.pathPending)
    3.     Debug.Log("Reload Level");
    4.  
    If this is not enough you can try checking pathStatus too.
     
  5. Angela_

    Angela_

    Joined:
    Feb 24, 2014
    Posts:
    9
    Thank you!
    I use this method now and it works

    Code (CSharp):
    1. private bool isAtTargetLocation(NavMeshAgent navMeshAgent, Transform moveTarget, float minDistance)
    2.     {
    3.         float dist;
    4.    
    5.         //-- If navMeshAgent is still looking for a path then use line test
    6.         if(navMeshAgent.pathPending)
    7.         {
    8.             dist = Vector3.Distance(transform.position, moveTarget.position);
    9.         }
    10.         else
    11.         {
    12.             dist = navMeshAgent.remainingDistance;
    13.         }
    14.         distanse = dist;
    15.         return dist <= minDistance;
    16.  
    17.     }
     
    Fraconte likes this.
  6. Ziplock9000

    Ziplock9000

    Joined:
    Jan 26, 2016
    Posts:
    360
    This is not a good solution. It only takes into account "how the crow flies", so if there's a 200 meter wall between close objects, it wont take this into account.