Unity3D游戏开发之UGUI实现伤害数值显示
发表于2017-08-31
下面就大家介绍的是使用Unity3D引擎做游戏开发时如何利用UGUI实现伤害数值显示,会的开发者都知道UGUI实现伤害数值显示的原理是在人物头顶放置空物体,然后将下面的脚本挂在空物体上,将该空物体制作为预制体;
代码如下:
using UnityEngine; using System.Collections; public class PopupDamage : MonoBehaviour { //目标位置 private Vector3 mTarget; //屏幕坐标 private Vector3 mScreen; //伤害数值 public int Value; //文本宽度 public float ContentWidth = 100; //文本高度 public float ContentHeight = 50; //GUI坐标 private Vector2 mPoint; //销毁时间 public float FreeTime = 1.5F; void Start() { //获取目标位置 mTarget = transform.position; //获取屏幕坐标 mScreen = Camera.main.WorldToScreenPoint(mTarget); //将屏幕坐标转化为GUI坐标 mPoint = new Vector2(mScreen.x, Screen.height - mScreen.y); //开启自动销毁线程 StartCoroutine("Free"); } void Update() { //使文本在垂直方向山产生一个偏移 transform.Translate(Vector3.up * 1.5F * Time.deltaTime); //重新计算坐标 mTarget = transform.position; //获取屏幕坐标 mScreen = Camera.main.WorldToScreenPoint(mTarget); //将屏幕坐标转化为GUI坐标 mPoint = new Vector2(mScreen.x, Screen.height - mScreen.y); } void OnGUI() { //保证目标在摄像机前方 if (mScreen.z > 0) { //内部使用GUI坐标进行绘制 GUIStyle style = new GUIStyle(); style.fontSize = 30; style.normal.textColor = Color.red; GUI.Label(new Rect(mPoint.x, mPoint.y, ContentWidth, ContentHeight), "-" Value.ToString(),style); } } IEnumerator Free() { yield return new WaitForSeconds(FreeTime); Destroy(this.gameObject); } }
Unity中的几种坐标体系:
1、根据Transform组件获取位置坐标,将此坐标转化为屏幕坐标及GUI坐标。
2、Unity3D中常见的四种坐标系:
a、世界坐标:场景中物体的坐标,使用 transform.position获得。
b、屏幕坐标:以像素来定义的,以屏幕的左下角为(0,0)点,右上角为(Screen.width,Screen.height),Z的位置是以相机的世界单位来衡量的。如Input.mousePosition即为屏幕坐标。
c、视口坐标:视口坐标是标准的和相对于相机的。相机的左下角为(0,0)点,右上角为(1,1)点,Z的位置是以相机的世界单位来衡量的。
d、GUI坐标:该坐标系以屏幕的左上角为(0,0)点,右下角为(Screen.width,Screen.height)。
3、在代码中我们将世界坐标先转化为屏幕坐标,再转化为GUI坐标
在人物受到伤害是,生成该预制体,方法如下:
GameObject damageGo = Instantiate(popupDamageGo,transform.position new Vector3(0,10,0),Quaternion.identity) as GameObject; damageGo.GetComponent().Value = (int)damage;