Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Adding Force to Rigidbody of NavMeshAgent

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

  1. mrCharli3

    mrCharli3

    Joined:
    Mar 22, 2017
    Posts:
    976
    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

    Joined:
    Apr 11, 2010
    Posts:
    29,723
    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:
    976
    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
     
    BigRookGames likes this.
  4. BigRookGames

    BigRookGames

    Joined:
    Nov 24, 2014
    Posts:
    330
    Having implemented that a while ago, did you ever find any issues with that solution? or is it working pretty well?