跑步的基本动画

此代码显示 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);
            }
        }

    }

   
}

http://i.stack.imgur.com/1cvGG.jpg