Mecanim walk to target position

Hi,

I am trying to make my Mecanim character to walk to a position in world space, in some event. How would I make the character walk to that position, and follow it even if the position was changed?

Thanks in advance!

Since you mention Mecanim, I’m guessing you want the animation ‘walk’ to play while the character moves?

First you’ll need to make the character move automatically. For that, define a variable Vector3 with the position you’d like the character to walk to. (You could use a NavMeshAgent as well).

To ensure that Mecanim responds with the proper animation, you’ll need to get the delta movement of the character, and delta rotation. For that, save the variable Vector3 Position of the character, and compare that with the last one…

Something like:

var currentPos : Vector3;   // Current position of the player
var playerAnimator : Animator;   // Assign this in the inspector

function Update () {
  if (currentPos) // won't run on the first frame if currentPos is null)
  {
    var currentVelocity = Vector3.Distance(transform.position, currentPos);    // gets the amount the character moved in the last frame
    currentPos = transform.position;  // reset
    playerAnimator.SetFloat("velocity", currentVelocity);		// Pass currentVelocity to Animator
  }
}

Do something similar for the rotation. This way the animations, controlled by Velocity and a variable for turning amount (X/Y, basically), can be adjusted when the player isn’t pressing controller buttons, and the animations will play properly.

Keep in mind RootMotion won’t work with this setup, since the actual movement of the player is being controlled by the NavMesh or through direct code.