1. 程式人生 > >【NGUI】NGUI血條製作,當人物移出屏幕後不顯示血條,優化程式碼

【NGUI】NGUI血條製作,當人物移出屏幕後不顯示血條,優化程式碼

using UnityEngine;
using System.Collections;
/// <summary>
/// 指令碼功能:NGUI血條實現
/// 知識要點:NGUI,3D座標到2D座標的轉換
/// 建立時間:2015年6月29日
/// 新增物件:新增到玩家身上
/// </summary>
public class HP_2 : MonoBehaviour
{
	// 玩家
	Transform Player;
	// 血條的UI
	public Transform Hp_UI;
	// 人物頭頂空物體(用於固定血條位置,這個空物體是人物的子物體)
	Transform Head;
	// 主攝像機與血條之間的距離
	float Distance;
	// 血條UI是否可見(當人物移動到螢幕外方的時候為不可見)
	bool uiIsCanSee = true;

	// 當掛載這個指令碼的物體在場景裡可以看見的時候
	void OnBecameVisible ()
	{
		uiIsCanSee = true;
	}
	// 當掛載這個指令碼的物體在場景裡看不見的時候
	void OnBecameInvisible ()
	{
		uiIsCanSee = false;
	}

	void Start ()
	{
		// 獲取掛載這個指令碼的玩家的Transform
		Player = gameObject.transform.GetComponent<Transform> ();
		// 找到玩家自身頭頂的空物體
		Head = Player.Find ("target");
		// 計算頭頂空物體與主攝像機之間距離
		Distance = Vector3.Distance (Head.position, Camera.main.transform.position);
	}
	

	void Update ()
	{
		// 如果玩家在攝像機的視線內,就顯示血條
		if (uiIsCanSee) {
			Hp_UI.gameObject.SetActive (true);
		} else {
			Hp_UI.gameObject.SetActive (false);
		}	
		// 計算縮放比例
		float newDistance = Distance / Vector3.Distance (Head.position, Camera.main.transform.position);
		// 血條UI的座標,由人物頭頂的空物體座標換算而來
		Hp_UI.position = WorldPointToUiPoint (Head.position);
		// 血條UI的縮放
		Hp_UI.localScale = Vector3.one * newDistance;


		if (Input.GetKey (KeyCode.W)) {
			gameObject.transform.Translate (Vector3.forward);
		}
		if (Input.GetKey (KeyCode.A)) {
			gameObject.transform.Translate (Vector3.left);
		}
		if (Input.GetKey (KeyCode.S)) {
			gameObject.transform.Translate (Vector3.back);
		}
		if (Input.GetKey (KeyCode.D)) {
			gameObject.transform.Translate (Vector3.right);
		}

	}

	// 主攝像機中物體的3D座標--->UI攝像機的3D座標
	public static Vector3 WorldPointToUiPoint (Vector3 point)
	{
		// 主攝像機中物體的3D座標轉換到主攝像機的2D座標
		Vector3 main_point_2d = Camera.main.WorldToScreenPoint (point);
		// 主攝像機中物體的2D座標轉換到UI攝像機的3D座標
		Vector3 ui_point_3d = UICamera.mainCamera.ScreenToWorldPoint (main_point_2d);
		// UI上的物體座標不涉及Z軸,所以要設為0
		ui_point_3d.z = 0;
		return ui_point_3d;
	}
}