This code shows a simple example of animation in Unity.
For this example, you should have 2 animation clips; Run and Idle. Those animations should be Stand-In-Place motions. Once the animation clips are selected, create an Animator Controller. Add this Controller to the player or game object you want to animate.
Open the Animator window from Windows option. Drag the 2 animation clips to the Animator window and 2 states would be created. Once created, use the left parameters tab to add 2 parameters, both of them as bool. Name one as "PerformRun" and other as "PerformIdle". Set "PerformIdle" to true.
Make transitionsfrom Idle state to Run and Run to idle (Refer the image). Click on Idle->Run transition and in the Inspector window, de-select HasExit. Do the same for the other transition. For Idle->Run transition, add a condition: PerformIdle. For Run->Idle, add a condition: PerformRun. Add the C# script given below to the game object. It should run with animation using the Up button and rotate with Left and Right buttons.
using UnityEngine;
using System.Collections;
public class RootMotion : MonoBehaviour {
//Public Variables
[Header("Transform Variables")]
public float RunSpeed = 0.1f;
public float TurnSpeed = 6.0f;
Animator animator;
void Start()
{
/**
* Initialize the animator that is attached on the current game object i.e. on which you will attach this script.
*/
animator = GetComponent<Animator>();
}
void Update()
{
/**
* The Update() function will get the bool parameters from the animator state machine and set the values provided by the user.
* Here, I have only added animation for Run and Idle. When the Up key is pressed, Run animation is played. When we let go, Idle is played.
*/
if (Input.GetKey (KeyCode.UpArrow)) {
animator.SetBool ("PerformRun", true);
animator.SetBool ("PerformIdle", false);
} else {
animator.SetBool ("PerformRun", false);
animator.SetBool ("PerformIdle", true);
}
}
void OnAnimatorMove()
{
/**
* OnAnimatorMove() function will shadow the "Apply Root Motion" on the animator. Your game objects psoition will now be determined
* using this fucntion.
*/
if (Input.GetKey (KeyCode.UpArrow)){
transform.Translate (Vector3.forward * RunSpeed);
if (Input.GetKey (KeyCode.RightArrow)) {
transform.Rotate (Vector3.up * Time.deltaTime * TurnSpeed);
}
else if (Input.GetKey (KeyCode.LeftArrow)) {
transform.Rotate (-Vector3.up * Time.deltaTime * TurnSpeed);
}
}
}
}