1. 程式人生 > >Unity外掛之NGUI學習(9)—— Tween和世界座標系尺寸轉換為NGUI尺寸

Unity外掛之NGUI學習(9)—— Tween和世界座標系尺寸轉換為NGUI尺寸

在遊戲中,有一種比較常見的動畫效果,就是產生得分後,分數會在遊戲中顯示,並快速移動到總分的位置並使之相加。今天我就打算使用NGUI的Tween來製作這種分數動畫效果。

根據 Unity外掛之NGUI學習(2),建立一個UI Root,然後使用NGUI建立一個Label和一個Button。


在Project視窗中,在Resources/Prefabs資料夾中建立一個Prefab,該Prefab就是一個NGUI的Label,然後在選單中選擇NGUI->Tween->Rotation和NGUI->Tween->Position



Play Style表示動畫播放方式。

Animation Curve

動畫速度曲線,點選後可以自定義。

Duration指定一次動畫的時長。Start Delay進行延遲play。秒為單位。

Tween Group表示漸變動畫組ID。

Ignore TimeScale是否忽略TimeScale。

Tween Rotation

FromTo,分別設定該GameObject開始和結束時在x,y,z上的旋轉角度,現在我在To的z軸上設定了-720,表示該物體會在z軸上按順時針旋轉2圈。

Tween Position

FromTo,分別設定該GameObject開始和結束時在x,y,z上的座標,該值為NGUI下的座標系,這裡暫且不設定To的座標值,後面會在程式碼中進行設定。


在Project視窗中建立一個TweenTest的指令碼檔案,程式碼如下:

using UnityEngine;
using System.Collections;


public class TweenTest : MonoBehaviour {


private GameObject prefab;
private UIButton btn;
private UILabel scoreLabel;
private int score;
private int add;
private GameObject addscore;


void Awake() {

// 預先建立好常用的得分Prefab
prefab = (GameObject)Resources.Load("Prefabs/AddScore");
}


// Use this for initialization
void Start () {
score = 1000;
btn = GameObject.Find("Button").GetComponent<UIButton>();
scoreLabel = GameObject.Find("Score").GetComponent<UILabel>();
scoreLabel.text = "" + score;

// 設定按鈕響應函式
EventDelegate.Add(btn.onClick, AddScore);
}

// Update is called once per frame
void Update () {

}


void AddScore() {

// 克隆得分GameObject
addscore = (GameObject)Instantiate(prefab, new Vector3(0, 0, 0), transform.rotation);
UILabel addlabel = addscore.GetComponent<UILabel>();
System.Random random = new System.Random();

// 隨機得分數
add = random.Next(50, 100);
addlabel.text = "" + add;

// 獲取TweenPosition物件
TweenPosition tweenP = addscore.GetComponent<TweenPosition>();

// 設定To的座標值,該值為NGUI的座標系的值,所以需要逆轉world座標值transform.InverseTransformPoint
tweenP.to = transform.InverseTransformPoint(scoreLabel.transform.position);
Debug.Log(tweenP.to.ToString());

// 設定動畫播放結束後的回撥函式
EventDelegate.Add(tweenP.onFinished, ScoreMoveFinished);

// 在Inspector視窗Tween Position選去掉了指令碼名字那裡的複選框,所以Tween Position不會執行,需要手動Play
tweenP.Play();
}


void ScoreMoveFinished() {
score += add;
scoreLabel.text = "" + score;
Destroy(addscore);
}
}

其中關鍵的程式碼就是tweenP.to = transform.InverseTransformPoint(scoreLabel.transform.position);因為Tween Position的To,From的值是基於NGUI的座標系,而我能目前能取得的是scoreLabel.transform.position,它是世界座標系的值,所以需要轉換為NGUI座標系的值。這正好是(8)中座標系的逆轉。

然後將指令碼新增到UI Root下,執行後,點選按鈕就會在中間隨機產生一個分數,然後會快速旋轉並移動到總分的位置,並使總分累加。