unity之Mecanim动画系统学习(4)
人物动画控制播放
以上动画包括静立/向前走/向左走/向右走/向后走/向前奔跑,通过箭头来进行状态过渡
并且,可以通过设置参数来控制动画什么时候进入下一状态,动画的播放参数等
比如下面一段比较笨的代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CharacterMove : MonoBehaviour
{
private Animator animator;
private bool LeftShift = false;
private void Start()
{
animator = this.GetComponent<Animator>();
}
private void Update()
{
Controll();
}
public void Controll()
{
if (Input.GetKeyDown(KeyCode.W))
{
animator.SetBool("walk_front",true);
}
if(Input.GetKeyUp(KeyCode.W))
{
animator.SetBool("walk_front",false);
}
if (Input.GetKeyDown(KeyCode.A))
{
animator.SetBool("walk_left", true);
}
if (Input.GetKeyUp(KeyCode.A))
{
animator.SetBool("walk_left", false);
}
if (Input.GetKeyDown(KeyCode.D))
{
animator.SetBool("walk_right", true);
}
if (Input.GetKeyUp(KeyCode.D))
{
animator.SetBool("walk_right", false);
}
if (Input.GetKeyDown(KeyCode.S))
{
animator.SetBool("walk_back", true);
}
if (Input.GetKeyUp(KeyCode.S))
{
animator.SetBool("walk_back", false);
}
if (LeftShift==true )
{
animator.SetBool("run",true);
Debug.Log("unity");
}
if ( LeftShift == false )
{
animator.SetBool("run",false);
}
if(Input.GetKeyDown(KeyCode.LeftShift))
{
LeftShift = true;
Debug.Log(LeftShift);
}
if (Input.GetKeyUp(KeyCode.LeftShift))
{
LeftShift = false ;
Debug.Log(LeftShift);
}
if(Input.GetKeyDown(KeyCode.J))
{
Debug.Log("j");
}
if (Input.GetKeyDown(KeyCode.J)&&Input .GetKeyDown(KeyCode.K))
{
Debug.Log("jk");
}
}
}
通过这些代码,就能够实现键盘对人物的前后左右移动
State Machine Behavior
我们也可以通过添加State Machine Behavior增加行为
以下是中文翻译后的代码注释
```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class walk_front : StateMachineBehaviour
{
//OnStateEnter is called when a transition starts and the state machine starts to evaluate this state
override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
//进入当前状态时会被调用
}
//OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks
override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
//进入当前状态的每帧会被调用
}
//OnStateExit is called when a transition ends and the state machine finishes evaluating this state
override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
//退出当前状态时会被调用
}
//OnStateMove is called right after Animator.OnAnimatorMove()
override public void OnStateMove(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
}
//OnStateIK is called right after Animator.OnAnimatorIK()
override public void OnStateIK(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
}
}
通过使用State Machine Behaviour我们可以更加方便的在特定的时间点触发一些我们需要的事件,但是需要注意的是,我们一般给State Machine Behaviour赋值一些场景的对象不是直接在Inspector面板里拖拽而是通过Animator的GetBehavior方法获取到指定的State Machine Behaviour的实例后通过脚本进行赋值的(这有别于平时的C#代码,当然,这样做其实代码执行效率会高一些)。