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

Navmesh agent strafing with mecanim

Discussion in 'Scripting' started by RichardsonKevin, Oct 21, 2014.

  1. RichardsonKevin

    RichardsonKevin

    Joined:
    Feb 3, 2013
    Posts:
    43
    Hello!

    I am trying to get my AI to strafe left and right and move forwards and backwards.

    I have updateRotation turned to false on my NavMeshAgent.

    I set up an Animator with a 2D Freeform Cartesian Blend tree.

    I have an idle animation set at the 0X,0Y position.

    I have the run animation set at the 0X,1Y position and the run backwards animation set at the 0X,-1Y.

    I also have the strafe left and right animations set up similarly along the X positions.

    I am using a function called NavAnimationSetup() that is called in the Update() function.

    Here it is...

    Code (CSharp):
    1. void NavAnimationSetup()
    2.     {
    3.  
    4.         float forwardSpeed;
    5.  
    6.         forwardSpeed = Vector3.Project (nav.desiredVelocity, transform.right).magnitude;
    7.  
    8.         Debug.Log (forwardSpeed);
    9.  
    10.         anim.SetFloat ("forwardSpeed", forwardSpeed);
    11.  
    12.         float sideSpeed;
    13.  
    14.         sideSpeed = Vector3.Project (nav.desiredVelocity, transform.forward).magnitude;
    15.        
    16.         anim.SetFloat ("sidewaysSpeed", sideSpeed);
    17.  
    18.     }
    19.  
    The forward animation and the strafe right animations work fine but if the navigation's destination point is behind the player it will not play the backwards animation, but instead play the forwards animation. Same thing happens to the strafing animation if the point is to the left. It will play the strafe right animation.

    The Debug.Log for forward speed never returns a negative value.

    I am wondering if anyone knows of an alternate way to get this to work or to get strafing to work with the NavMeshAgent and Mecanim in a completely different way. Any help would be appreciated!
     
  2. RichardsonKevin

    RichardsonKevin

    Joined:
    Feb 3, 2013
    Posts:
    43
    Nevermind! I just find the angle from the next steering target and see if it is in front or behind. then multiply by negative if it is.