標籤:style blog http color io os 使用 ar for
許多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; }}View Code
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); }}View Code
6,運行效果:
7,點擊物體類比被攻擊,看血量減少,並彈出被攻擊值。
玩家掛了
項目源碼:
連結:http://pan.baidu.com/s/1jGDpZF4 密碼:vh5p
如果打不開,請檢查Unity版本哦,本人測試的是4.5.
玩家資訊血條及傷害值隨主角移動