Unity——傷害數字顯示HUD
傷害數字顯示HUD
遊戲中收到傷害掉血,會有飄動的傷害數值;
可以使用OnGUI中GUI.Label來實現;
可自定義字體,顏色,大小等;
如果需要更好看的數字特效,可以手動添加;
普通字體不夠好看可以使用插件FontEditor自定義;
Demo展示

HUDPopup類
飄血數字類,創建一個空物體,將這個腳本掛上去,再將這個物體拖成預製體;
public class HUDPopup : MonoBehaviour
{
//目標位置
private Vector3 mTarget;
//螢幕坐標
private Vector3 mScreen;
//傷害數值
public int Value;
//文本寬度
public float ContentWidth;
//文本高度
public float ContentHeight;
//GUI坐標
private Vector2 mPoint;
//銷毀時間
public float FreeTime = 1.5F;
public Font font;
public Color color;
public int fontSize;
public float speed;
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 * speed * 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 = fontSize;
style.font = font;
style.normal.textColor = color;
GUI.Label(new Rect(mPoint.x, mPoint.y, ContentWidth, ContentHeight), "-"+Value.ToString(),style);
}
}
IEnumerator Free()
{
yield return new WaitForSeconds(FreeTime);
Destroy(this.gameObject);
}
}
一些自定義屬性,默認Color的透明度是0,如果出現不顯示,可以看看這裡;

使用時,在需要有掉血數字的物體上的腳本中實例化HUDPopup,創一個HUD預製體對象,放在該物體的子節點下某個位置(一般在怪物頭頂創建一個空節點,用來當HUD的父物體);

測試類程式碼:
public class Test : MonoBehaviour
{
public GameObject popupDamage;
public Transform hudPos;
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
GameObject mObject = (GameObject)Instantiate(popupDamage, hudPos.position, Quaternion.identity);
mObject.GetComponent<HUDPopup>().Value = Random.Range(20, 40);
}
}
}


