using UnityEngine; using System.Collections; public class NPC : MonoBehaviour { //主攝像機對象 private Camera camera; //NPC名稱 private string name = "我是雨鬆MOMO"; //主角對象 GameObject hero; //NPC模型高度 float npcHeight; //紅色血條貼圖 public Texture2D blood_red; //黑色血條貼圖 public Texture2D blood_black; //默認NPC血值 private int HP = 100; void Start () { //根據Tag獲得主角對象 hero = GameObject.FindGameObjectWithTag("Player"); //獲得攝像機對象 camera = Camera.main; //註解1 //獲得模型原始高度 float size_y = collider.bounds.size.y; //獲得模型縮放比例 float scal_y = transform.localScale.y; //它們的乘積就是高度 npcHeight = (size_y *scal_y) ; } void Update () { //保持NPC一直面朝主角 transform.LookAt(hero.transform); } void OnGUI() { //獲得NPC頭頂在3D世界中的座標 //默認NPC座標點在腳底下,因此這裏加上npcHeight它模型的高度便可 Vector3 worldPosition = new Vector3 (transform.position.x , transform.position.y + npcHeight,transform.position.z); //根據NPC頭頂的3D座標換算成它在2D屏幕中的座標 Vector2 position = camera.WorldToScreenPoint (worldPosition); //獲得真實NPC頭頂的2D座標 position = new Vector2 (position.x, Screen.height - position.y); //註解2 //計算出血條的寬高 Vector2 bloodSize = GUI.skin.label.CalcSize (new GUIContent(blood_red)); //經過血值計算紅色血條顯示區域 int blood_width = blood_red.width * HP/100; //先繪製黑色血條 GUI.DrawTexture(new Rect(position.x - (bloodSize.x/2),position.y - bloodSize.y ,bloodSize.x,bloodSize.y),blood_black); //在繪製紅色血條 GUI.DrawTexture(new Rect(position.x - (bloodSize.x/2),position.y - bloodSize.y ,blood_width,bloodSize.y),blood_red); //註解3 //計算NPC名稱的寬高 Vector2 nameSize = GUI.skin.label.CalcSize (new GUIContent(name)); //設置顯示顏色爲黃色 GUI.color = Color.yellow; //繪製NPC名稱 GUI.Label(new Rect(position.x - (nameSize.x/2),position.y - nameSize.y - bloodSize.y ,nameSize.x,nameSize.y), name); } //下面是經典鼠標點擊對象的事件,你們看一下就應該知道是什麼意思啦。 void OnMouseDrag () { Debug.Log("鼠標拖動該模型區域時"); } void OnMouseDown() { Debug.Log("鼠標按下時"); if(HP >0) { HP -=5 ; } } void OnMouseUp() { Debug.Log("鼠標擡起時"); } void OnMouseEnter() { Debug.Log("鼠標進入該對象區域時"); } void OnMouseExit() { Debug.Log("鼠標離開該模型區域時"); } void OnMouseOver() { Debug.Log("鼠標停留在該對象區域時"); } }