跑步的基本動畫
此程式碼顯示 Unity 中的動畫的簡單示例。
對於此示例,你應該有 2 個動畫片段; 跑步和空閒。這些動畫應該是 Stand-In-Place 動作。選擇動畫片段後,建立 Animator Controller。將此 Controller 新增到要設定動畫的播放器或遊戲物件。
從 Windows 選項開啟 Animator 視窗。將 2 個動畫片段拖動到 Animator 視窗,將建立 2 個狀態。建立後,使用左引數選項卡新增 2 個引數,兩個引數均為 bool。將其命名為 PerformRun
,將其他命名為 PerformIdle
。將 PerformIdle
設定為 true。
從空閒狀態轉換到執行並執行到空閒(參見影象)。單擊 Idle-> Run transition,然後在 Inspector 視窗中取消選擇 HasExit。對其他過渡做同樣的事情。對於空閒 - >執行轉換,新增條件:PerformIdle。對於 Run-> Idle,新增一個條件:PerformRun。將下面給出的 C#指令碼新增到遊戲物件中。它應該使用向上按鈕執行動畫,並使用向左和向右按鈕旋轉。
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);
}
}
}
}