認識Blend Tree
我們在Animator Controller中除了可以創建一個State外還可以創建一個Blend Tree,如下:
那么我們看下新創建的Blend Tree和State有什么區別:
唯一的區別就是Montion指向的類型變成了Blend Tree類型,那么一個Blend Tree其實也就是一個狀態,和狀態不同的地方就是一個狀態只能設定一個動畫,而一個Blend Tree則可以設定為多個動畫的混合。
混合樹是Mecanim動畫系統中比較復雜的一個內容,且其分為多個維度,下面我們逐個的來進行學習。
一維混合樹
我們以官方的例子使用一維混合樹來實現下面的效果:我們人物的跑動分為3個動畫,分別是向前跑、向左跑和向右跑,其中向左跑和向右跑人物都會有一定的傾斜,這樣更加符合現實的情況,那么我們在狀態機中跑動只有一個狀態,所以我們的跑動需要設置為混合樹來混合這3個動畫。
首先我們需要創建一個新的場景,拖入我們的人物模型,然后創建一個Animator Controller並對其進行配置:
注意我們的Run是Blend Tree而不是State,雙擊Run就可以進入混合樹的編輯界面。
右擊我們的混合樹添加3個Motion,如下:
同時我們設定好3個方向的跑動動畫:
我們還需要設定一個名為Direction的Float類型的參數來控制這個混合樹:
接下來我們取消Automate Thresholds的選項,並按下圖進行選擇,系統會為我們配置好閥值:
現在我們點擊預覽框查看動畫播放時就可以通過拖拽小紅線來看不同的變化了,我們的可使用的角度范圍為-130到130之間。
到現在我們的動畫控制器就配置好了。
腳本
下面我們使用腳本來控制一下人物,我們給人物添加下面的腳本即可:
1 using UnityEngine; 2 using System.Collections; 3 4 public class TestBlendTree : MonoBehaviour 5 { 6 public float DirectionDampTime = 30.0f; 7 8 private Animator _animator; 9 10 void Start() 11 { 12 _animator = this.GetComponent<Animator>(); 13 } 14 15 void Update() 16 { 17 if(Input.GetKeyDown(KeyCode.W)) 18 { 19 _animator.SetBool("run", true); 20 } 21 if(Input.GetKeyUp(KeyCode.W)) 22 { 23 _animator.SetBool("run", false); 24 } 25 26 AnimatorStateInfo state = _animator.GetCurrentAnimatorStateInfo(0); 27 //奔跑狀態下才允許轉彎 28 if(state.shortNameHash == Animator.StringToHash("Run")) 29 { 30 //指定人物轉彎通過控制混合數的參數即可 31 float h = Input.GetAxis("Horizontal") * 130.0f; 32 //DirectionDampTime 指示了每秒可以到達的最大值 33 //deltaTime 表示當前幀的時間 34 _animator.SetFloat("Direction", h, DirectionDampTime, Time.deltaTime); 35 } 36 else 37 { 38 //重置一下參數 39 _animator.SetFloat("Direction", 0); 40 } 41 } 42 }
為了讓攝像機跟隨人物,我們直接添加官方給出的這個腳本到攝像機上即可:
1 using UnityEngine; 2 using System.Collections; 3 4 public class ThirdPersonCamera : MonoBehaviour 5 { 6 public float distanceAway; // distance from the back of the craft 7 public float distanceUp; // distance above the craft 8 public float smooth; // how smooth the camera movement is 9 10 private GameObject hovercraft; // to store the hovercraft 11 private Vector3 targetPosition; // the position the camera is trying to be in 12 13 Transform follow; 14 15 void Start(){ 16 follow = GameObject.FindWithTag ("Player").transform; 17 } 18 19 void LateUpdate () 20 { 21 // setting the target position to be the correct offset from the hovercraft 22 targetPosition = follow.position + Vector3.up * distanceUp - follow.forward * distanceAway; 23 24 // making a smooth transition between it's current position and the position it wants to be in 25 transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * smooth); 26 27 // make sure the camera is looking the right way! 28 transform.LookAt(follow); 29 } 30 }
記得將人物的Tag設置為Player,同時腳本也要設置一下:
動畫方面的一點要求
每個混合樹的動畫有一些要注意的地方:
- 動畫長度需要一致;
- 動畫的起始姿勢需要一致;
二維混合樹
同1維混合樹,不過二維混合樹已經作為一個平面來處理,同時需要兩個參數來進行控制。對於更復雜的動畫融合可以使用該模式,這里就不深入學習了。
我們可以將兩個1維混合樹合並為一個2維混合樹來控制。
多維混合樹
多維混合樹在Unity5時添加,其配置更加復雜,一般使用在臉部表情的動畫融合上。