Search Unity

Using Rigidbody.AddForce with a NavmeshAgent.

Discussion in 'Navigation' started by mrCharli3, May 19, 2019.

  1. mrCharli3

    mrCharli3

    Joined:
    Mar 22, 2017
    Posts:
    365
    Can't seem to get any of the suggestions I find to this question to work. I have an agent that follows my player, I want to push back that agent when it hits my player, and that works, but the agents position does not seem to update correctly, since after the collision it does not properly try to get to the Player again, like it thinks it's reached its position.

    It also says in Unity docs that I need to set the RigidBody to Kinematic, but then I can't add force to it?

    Code (CSharp):
    1. private void Update()
    2.     {
    3.         if (!playerHit && followPlayer)
    4.         {
    5.             _agent.SetDestination(GameManager.instance.ActivePlayer.transform.position);
    6.         }
    7.     }
    8.  
    9.     private void FixedUpdate()
    10.     {
    11.         if (playerHit)
    12.         {
    13.             _rb.AddForce(-transform.forward * 10, ForceMode.Impulse);
    14.         }
    15.     }
     
  2. Yandalf

    Yandalf

    Joined:
    Feb 11, 2014
    Posts:
    300
    Indeed, the NavMesh system does not play nicely with physics in general.
    What is basically happening is two separate systems (Navigation and Physics) both trying to change and read the position. They simply go out of sync. You could do the following:
    -When the hit happens, turn off the NavMeshAgent and turn the Rigidbody's IsKinematic off.
    -Apply the force to the Rigidbody.
    -Once the Rigidbody has slowed down enough from the knockback, reverse the first step.
    -Set a new path for the agent to continue moving.