Search Unity

Using Rigidbody physics to move an enemy with NavMeshAgent - De-sync issues

Discussion in 'Navigation' started by Pixelch3f, Mar 17, 2018.

  1. Pixelch3f

    Pixelch3f

    Joined:
    Sep 2, 2017
    Posts:
    12
    Hi,

    I have some simple code for an enemy in my game, where the enemy will roam around the level using NavMesh or chase the player if they get close enough.

    The thing is, I need the enemy to be affected by physics, because the player has a rocket launcher which applies knockback force to the enemy.

    So what I did was instead of using the NavMeshAgent to move the enemy, I set UpdatePosition to false, and just used the path finding of the agent to move the enemy using the rigidbody. The problem I have is that often the enemy and the agent component become separated by some means (this could be if the enemy goes over a ramp, the rigidbody component will slow the enemy down, but the agent component will keep going, so the agent is then in a different position). Here is the relevant code:

    Code (csharp):
    1.  
    2. void Awake()
    3.      {
    4.          navAgent = GetComponent<NavMeshAgent>();
    5.          rb = GetComponent<Rigidbody>();
    6.          target = GameObject.FindGameObjectWithTag("Player").transform;
    7.          // set NavAgent to not update position, this is done by Rigidbody movement
    8.          navAgent.updatePosition = false;
    9.          navAgent.updateRotation = true;
    10.      }
    11.  
    12.  void FixedUpdate()
    13.      {
    14.          /* Enemy Movement */
    15.          // Manually move the Rigidbody using the calculated NavAgent velocity, this is so that the Enemy can be affected by force properly
    16.          rb.MovePosition(transform.position + navAgent.velocity * Time.fixedDeltaTime);
    17.      }
    18.  
    19.  void MoveToTarget()
    20.      {
    21.              // Calculate the path to the target
    22.              navAgent.nextPosition = transform.position;
    23.              navAgent.SetDestination(target.position);
    24.      }
    25.  
    So that's the code I use the move the enemy, any idea what i can do differently to stop this de-sync issue?

    Thanks in advance!
     
  2. SM_AF

    SM_AF

    Joined:
    Aug 1, 2017
    Posts:
    23
    - In case you are not using Rigidbody Interpolation, use 'rb.position = ' instead of 'rb.MovePosition()' (that way, you will always set it's position instantly)
    - It would be better to set rb.isKinematic to false and navAgent.updatePosition to false only when knockback is happening. After it finishes, set these properties to true again.
    - You could also alternatively put 'navAgent.nextPosition = rb.position;' to the FixedUpdate (right after the rb.position assignment)
     
    Last edited: Mar 28, 2018
    warpfx likes this.