Search Unity

Adding Force to Rigidbody of NavMeshAgent

Discussion in 'Navigation' started by mrCharli3, May 18, 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 want to push back my enemy 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. hippocoder

    hippocoder

    Digital Ape Moderator

    Joined:
    Apr 11, 2010
    Posts:
    25,219
    https://docs.unity3d.com/Manual/nav-MixingComponents.html

    In my case I do something similar to Agent follows animation but instead apply forces to my rigidbody.

    Note: the agent will keep it upright as well, so disable the agent if falling over is required for the rigidbody at any point.
     
  3. mrCharli3

    mrCharli3

    Joined:
    Mar 22, 2017
    Posts:
    365
    Thanks,

    I ended up doing something like this:

    Code (CSharp):
    1. _rb.isKinematic = false;
    2. _agent.enabled = false;
    3. _rb.AddForce(-transform.forward * 10, ForceMode.Impulse);
    4. //.....
    5. if(_rb.velocity.magnitude <= 0.1f)
    6. {
    7.     _rb.isKinematic = true;
    8.     _agent.enabled = true;
    9. }

    Its ok for what I need