Search Unity

Trying to get Nav Agent to Walk Backwards

Discussion in 'Navigation' started by jkuehlin, Dec 2, 2019.

  1. jkuehlin

    jkuehlin

    Joined:
    Sep 8, 2017
    Posts:
    6
    Trying to get an animal AI (a Siberian Tiger) to walk toward a cube. But if it sees a sphere come within a certain distance, to stop and take a few steps backwards.

    The problem is that when I move the sphere (manually for now) close to the Tiger, it turns and slerps away. I want it to move directly backwards while keeping the forward orientation toward the sphere.

    Screen Shot 2019-12-02 at 1.31.32 PM.png

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.AI;
    3.  
    4. public class TigerMovementTest : MonoBehaviour
    5. {
    6.     public Transform cube;
    7.     public Transform sphere;
    8.     NavMeshAgent agent;
    9.  
    10.     private void Start()
    11.     {
    12.         agent = this.GetComponent<NavMeshAgent>();
    13.     }
    14.  
    15.     private void LateUpdate()
    16.     {
    17.         agent.SetDestination(cube.position);
    18.  
    19.         float distance = Vector3.Distance(transform.position, sphere.transform.position);
    20.         float BackAway = 3.0f;
    21.  
    22.         if (distance < BackAway)
    23.         {
    24.             Vector3 dirToGoal = transform.position - sphere.transform.position;
    25.             Vector3 newPos = Vector3.back;
    26.             agent.SetDestination(newPos);
    27.         }
    28.    }
    29. }
     
  2. Olmi

    Olmi

    Joined:
    Nov 29, 2012
    Posts:
    589
    Hi @jkuehlin,

    If you want to move the agent backwards I think your only option is to take control of the situation and do it manually.

    Probably this means something like disabling the agent, then moving your object to the correct position manually.
    You could do this by calculating the position to be 2 meters behind the tiger and then lerp the position over time there.
    And if your animation is driven by a blend tree, then it's somewhat easy to get it behave ok, as your backwards walking would be automatically activated when you move the object backwards.
     
  3. vhman

    vhman

    Joined:
    Aug 13, 2018
    Posts:
    107
    Hi,

    After you triggers this event, I would recommend disable agent.updatePosition=false and agent.updateRotation=false, use agent.Move to move tiger backward, and revert all back.

    Or just agent.updateRotation=false, and move it by agent.setDestination, than agent.updateRotation=true

    Or tiger.Scale(-1,-1,1), agent.setDestination(), tiger.Scale(1,1,1), maybe make some rotation before.

    But yes, agent cannot crawl back)