参考链接:
http://www.cnblogs.com/hont/p/5100472.html
上一篇是直接通过界面来控制动作的播放,这篇将使用脚本去管理对象的动作
API解析:
Animator.IsInTransition:是否处于过渡状态
状态机如下:
脚本如下:
TestAnimator.cs
1 using UnityEngine; 2 3 public class TestAnimator : MonoBehaviour { 4 5 //------------------------------------------外部 6 public float Move = 0; 7 public bool IsDying = false; 8 9 //------------------------------------------内部 10 private Animator animator; 11 12 //常数 13 private int baseLayerIndex; 14 private int idleStateHash; 15 private int runStateHash; 16 private int dyingStateHash; 17 private string movePara; 18 private string isDyingPara; 19 20 void Start () 21 { 22 animator = GetComponent<Animator>(); 23 24 baseLayerIndex = animator.GetLayerIndex("Base Layer"); 25 idleStateHash = Animator.StringToHash("Base Layer.Idle"); 26 runStateHash = Animator.StringToHash("Base Layer.Run"); 27 dyingStateHash = Animator.StringToHash("Base Layer.Dying"); 28 movePara = "move"; 29 isDyingPara = "isDying"; 30 } 31 32 void Update () 33 { 34 //------------------------------------------播放动作 35 animator.SetFloat(movePara, Move); 36 if (IsDying) 37 { 38 animator.SetBool(isDyingPara, true); 39 IsDying = false; 40 } 41 42 //------------------------------------------动作恢复 43 AnimatorStateInfo stateInfo; 44 int fullPathHash; 45 46 //BaseLayer 47 stateInfo = animator.GetCurrentAnimatorStateInfo(baseLayerIndex); 48 if (!animator.IsInTransition(baseLayerIndex) && stateInfo.normalizedTime >= 1) 49 { 50 fullPathHash = stateInfo.fullPathHash; 51 if (fullPathHash == dyingStateHash) 52 { 53 animator.SetBool(isDyingPara, false); 54 } 55 } 56 } 57 58 public void SetDying(bool state) 59 { 60 if (animator) 61 { 62 animator.SetBool(isDyingPara, state); 63 } 64 } 65 }
NewBehaviourScript.cs
1 using UnityEngine; 2 3 public class NewBehaviourScript : MonoBehaviour { 4 5 public TestAnimator testAnimator; 6 7 void Update () 8 { 9 if (Input.GetKey(KeyCode.Q)) 10 { 11 testAnimator.Move = 1; 12 } 13 if (Input.GetKeyUp(KeyCode.Q)) 14 { 15 testAnimator.Move = 0; 16 } 17 if (Input.GetKeyDown(KeyCode.W)) 18 { 19 testAnimator.IsDying = true; 20 } 21 if (Input.GetKeyDown(KeyCode.E)) 22 { 23 testAnimator.SetDying(false); 24 } 25 } 26 }
按住Q,播放跑步动画;松开Q,播放站立动画;按下W,播放倒地动画;按下E,播放倒地恢复成站立的动画