Mecanim Animation From Transform

software
unity3d
In this post I will try to explain how I implemented simple auto animation for my characters based on their changing position in the scene (using mecanim and a simple script).


Position and Rotation only

In the above example the only thing being manipulated is the objects position and rotation (The animations are happening automagically)

How to

First we need to load a Mecanim Animator->Controller and a model to attach an Animator component onto. In my example I have used the classic unity model of Kyle the Robot and the standard ThirdPersonAnimatorController (Any model and controller will do).

Animation States and Variables

We can see that there are a few states and variables included in this controller. The variable we are interested in is Forward .

The value of Forward will determine the walk/run animation that mecanim wil animate for us.

The Code

using UnityEngine;
using System.Linq;

public class AnimationFromTransform : MonoBehaviour {

    public float MinMovementAmount = 1;
    public string MechanimMovementName = "Forward";
    private Animator _anim;
    void Start () {
        _prevPosition = Transform.position;
        _anim = GetComponentsInChildren<Animator>().FirstOrDefault();
        if(_anim == null)
        {
            _anim = GetComponent<Animator>();
        }
    }
    
    private Vector3 _prevPosition;
    void Update () {

        if (_anim != null)
        {
            Vector3 vel = (Transform.position - _prevPosition) / Time.timeScale;
            
            var movement = Mathf.Max(Mathf.Abs(vel.x), Mathf.Abs(vel.z));
            if (movement > 0f)
            {
                movement = Mathf.Max(MinMovementAmount, movement);
            }
                        
            _anim.SetFloat(MechanimMovementName, movement);

            _prevPosition = Transform.position;
        }
    }
}

Explanation

Each Update() the Velocity (Vector3) of the object is taken . This value is then passed to the animator (if one exists) which sets the specified movement float (" Forward " in my example)

Velocity

This is the difference between this frames transform and the previous frames transform.

Note

MinMovementAmount - This variable can be changed in order to get the desired effect. I found that a value of 1 produced good movements for the prototype I was implementing.

Usage

Simply attach this script to your object that contains your character. Good luck, let me know in the comments if anything needs explaining or if this does not work for you :)