許多RPG游戲中絕對少不了的就是玩家信息的動態顯示,包括玩家姓名,等級,生命值,被攻擊時生命值的減少等。
今天我們來共同學習一下怎么制作。搞起。。。。
1,首先導入NGUI,感覺NGUI做UI還是挺方便的。
2,創建玩家Player可用cube代替且在cube下創建子物體head位置默認值歸零,用途:玩家信息顯示位置。
3,使用NGUI創建玩家信息跟隨,結構如下:
4,貼代碼:NewBehaviourScript.cs掛到MainCamera上

using UnityEngine; using System.Collections; public class NewBehaviourScript : MonoBehaviour { //角色 public Transform Cube; //要歲主角移動的信息 血條,名稱 public Transform UI; //默認血條與攝像機的距離 private float Fomat; //角色頭頂位置 private Transform Head; void Start () { //找到角色頭頂點 Head = Cube.Find("head"); //計算一下默認血條的距離 Fomat = Vector3.Distance(Head.position,Camera.main.transform.position); Debug.Log (Fomat); } void Update () { //這里可以判斷一下,如果位置沒發生變化課不再賦值 float newFomat = Fomat / Vector3.Distance(Head.position,Camera.main.transform.position); UI.position = WorldToUI(Head.position); //計算血條的縮放比例 UI.localScale = Vector3.one * newFomat; //測試代碼 移動角色 if(Input.GetKey(KeyCode.W)) Cube.Translate(Vector3.forward); if(Input.GetKey(KeyCode.S)) Cube.Translate(Vector3.back); if(Input.GetKeyDown(KeyCode.A)) Cube.Translate(Vector3.left); if(Input.GetKeyDown(KeyCode.D)) Cube.Translate(Vector3.right); } //3D坐標轉換為NGUI屏幕上的2D坐標 public static Vector3 WorldToUI(Vector3 point) { Vector3 pt = Camera.main.WorldToScreenPoint(point); //UICamera.currentCamer Vector3 ff = UICamera.currentCamera.ScreenToWorldPoint(pt); //UI的Z軸為0 ff.z = 0; return ff; } }
5,另一個腳本cube.csgua掛在player上

using UnityEngine; using System.Collections; public class cube : MonoBehaviour { public GameObject fg; private GameObject sprite; public GameObject harm; public UILabel hp; // Use this for initialization void Start () { harm.SetActive(false); hp.text = "HP:100/100"; } // Update is called once per frame void Update () { } void OnMouseDown() { if(fg.GetComponent<UISprite>().fillAmount>0) { fg.GetComponent<UISprite>().fillAmount -= 0.1f; harm.SetActive(true); hp.text = ((int)(fg.GetComponent<UISprite>().fillAmount*100)).ToString()+"/100"; } Debug.Log (fg.GetComponent<UISprite>().fillAmount); } void OnMouseUp() { harm.SetActive(false); } }
6,運行效果:
7,點擊物體模擬被攻擊,看血量減少,並彈出被攻擊值。
玩家掛了
項目源碼:
鏈接:http://pan.baidu.com/s/1jGDpZF4 密碼:vh5p
如果打不開,請檢查Unity版本哦,本人測試的是4.5.