Unity 伤害数字显示
参考链接https://blog.csdn.net/book_longssl/article/details/39610775?utm_medium=distribute.pc_relevant.none-task-blog-baidujs_title-7&spm=1001.2101.3001.4242
试着做了下伤害数字的显示 效果如下
首先是新建一个c#脚本
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DamageGUI : MonoBehaviour
{
private Vector3 mTarget;
private Vector3 mScreen;
public float value;
public float ContentWidth = 100;
public float ContentHeight = 50;
private Vector2 mPoint; //GUI坐标
public float DestoryTime = 2.0f; //伤害数字消失时间
// Start is called before the first frame update
void Start()
{
mTarget = transform.position; //获取目标位置
mScreen = Camera.main.WorldToScreenPoint(mTarget); //转化为屏幕位置
mPoint = new Vector2(mScreen.x, Screen.height - mScreen.y);
StartCoroutine("Free"); //开启一个协程
}
// Update is called once per frame
void Update()
{
transform.Translate(Vector3.up * 0.5f * Time.deltaTime); //伤害数字上移效果
mTarget = transform.position;
mScreen = Camera.main.WorldToScreenPoint(mTarget);
mPoint = new Vector2(mScreen.x, Screen.height - mScreen.y);//实时变化位置
}
void OnGUI()
{
if (mScreen.z > 0) //伤害数字显示
{
GUI.Label(new Rect(mPoint.x, mPoint.y, ContentWidth, ContentHeight), value.ToString());
}
}
IEnumerator Free() //协程,伤害数字时间一到消失
{
yield return new WaitForSeconds(DestoryTime);
Destroy(this.gameObject);
}
}
随意新建一个空的物体
取名为DamageText,插入前面写好的DamageGUI脚本
并设为预制体,放入Resources文件夹
随后在人物的头顶位置Create Empty Object
我这里是新建了一个statusBar 以后也可以用于制作例如眩晕、减速等
随后在之前写好的战斗模块中调用这个DamageText预制体
public GameObject DamageGUI;
void Start()
{
DamageGUI = Resources.Load("DamageText") as GameObject;
}
public void AddHp(float value) {
GameObject DamageText = (GameObject)Instantiate(DamageGUI, transform.DeepFind("statusBar").gameObject.transform.position, Quaternion.identity);
DamageText.GetComponent<DamageGUI>().value = value;
}
调用这个预制体的脚本位于PlayerHandle这一层中
而初始的Damage GUI是空的,需要将预制体拖入,但为了不每次新建角色怪物时重新拖入,这里我使用了
DamageGUI = Resources.Load("DamageText") as GameObject;
从Resources资源文件夹获取之前放入的预制体,运行后就可以自动获取
同时生成伤害数字的起始位置也是向下搜索
transform.DeepFind("statusBar").gameObject.transform.position
DeepFind的代码如下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class TransformHelpers
{
public static Transform DeepFind(this Transform parent, string targetName) {
Transform tempTrans = null;
foreach (Transform child in parent)
{
if (child.name == targetName)
{
return child;
}
else {
tempTrans = DeepFind(child, targetName);
if (tempTrans != null) {
return tempTrans;
}
}
}
return tempTrans;
}
}
简单的白字伤害数字就此完成,此后还需添加样式,例如更改伤害数字的大小,应该是从跳出时最大,逐渐变小,同时如果是暴击,得变个颜色,而且随着时间渐渐透明等,留待以后完成。