Unity3d GUI人物的名称与hp的绘制方法

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("鼠标停留在该对象区域时");

//}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值