using UnityEngine;
using System.Collections;
public class NPC : MonoBehaviour
{
//主摄像机对象
private Camera camera;
//NPC名称
private string name = "name";
//NPC模型高度
float npcHeight;
//前景血条贴图
public Texture2D blood_fg;
//背景血条贴图
public Texture2D blood_bg;
//默认NPC血值
private int HP = 100;
void Start ()
{
blood_fg = Resources.Load<Texture2D> ("Textures/fg");
blood_bg = Resources.Load<Texture2D> ("Textures/bg");
//得到摄像机对象
camera = Camera.main;
//注解1
//得到模型原始高度
float size_y = transform.GetComponent<Collider> ().bounds.size.y;
//得到模型缩放比例
float scal_y = transform.localScale.y;
//它们的乘积就是高度
npcHeight = (size_y* scal_y)*0.2f ;
}
void OnGUI ()
{
if (HP <= 0) return;
//得到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_fg));
bloodSize = new Vector2 (20,2);
//通过血值计算红色血条显示区域
float blood_width = bloodSize.x * HP / 100;
//先绘制黑色血条
GUI.DrawTexture(new Rect (position.x - (bloodSize.x/2),position.y - bloodSize.y ,bloodSize.x,bloodSize.y),blood_bg);
//在绘制红色血条
GUI.DrawTexture(new Rect (position.x - (bloodSize.x/2),position.y - bloodSize.y ,blood_width,bloodSize.y),blood_fg);
注解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("鼠标停留在该对象区域时");
//}
}
Unity3d GUI人物的名称与hp的绘制方法
最新推荐文章于 2022-12-05 03:30:00 发布