Search Unity

understanding NavMeshAgent.updatePosition

Discussion in 'Navigation' started by FeastSC2, May 18, 2019.

  1. FeastSC2

    FeastSC2

    Joined:
    Sep 30, 2016
    Posts:
    978
    When I set NavMeshAgent.updatePosition = true my unit moves automatically AND the pathfinding understands where my unit is, even if I move its transform position in the editor. It is constantly updated.

    When I set NavMeshAgent.updatePosition = false, my unit is not moved automatically AND the pathfinding's path does not necessarily start from where my unit is. Especially if:
    1) I stopped using the pathfinding for a duration then started using it again.
    2) or that I just moved my unit in the editor using the transform.position.
    The picture below shows the problem I'm having: there is an offset between where my unit is and where the pathfinding thinks my unit is because I moved my unit's transform position in the editor.

    I wish to use my own Controller to move my units meaning that the pathfinding's updatePosition = false. However I would like that the pathfinding knows correctly where my unit is as if using updatePosition = true.
    Using NavMeshAgent.Warp(Unit.transform.position) makes the pathfinding understand where my unit is but it also stops any movement during that frame so I cannot call this every frame. I would have to only call it when the pathfinding is wrong about my unit's position.

    How can I know when to call Warp to sync the pathfinding to where my unit is?
    Or is there a better solution to have the pathfinding sync up to where my unit is without having the pathfinding move my unit?

    Unity_2019-05-18_13-57-08.png
     
  2. FeastSC2

    FeastSC2

    Joined:
    Sep 30, 2016
    Posts:
    978
    Ok I found a handy solution, but I don't know how expensive it is.

    I set the NavMeshAgent.updatePosition = true but on the NavMeshAgent component I set the speed to 0. Meaning that the agent won't be moved automatically BUT that the position of the agent will be updated in the pathfinding.

    And then to find where I must go with my custom Controller script I use one of the functions of the NavMeshAgent called SamplePathPosition.

    Here's a bit of code for anyone that would encounter this problem:

    Code (CSharp):
    1.                     if (U.Agent.remainingDistance > U.Agent.stoppingDistance)
    2.                     {
    3.                         var nextMovePoint = U.Agent.SamplePathPosition(NavMeshConstants.Walkable, PatrolSpeed, out var hit);
    4.                         U.Control.TurnThenMoveTowards(hit.position, PatrolSpeed);
    5.                     }
    Code (CSharp):
    1. public static class NavMeshConstants
    2. {
    3.     public static int Walkable = 1 << NavMesh.GetAreaFromName("Walkable");
    4. }