如何在遊戲畫面顯示擊殺或者傷害數值?關鍵在於獲取屏幕的座標,把屏幕座標轉換爲GUI的座標
明確幾個基本概念
世界座標:
transform.position獲取的是世界座標
屏幕座標:
單位像素
屏幕左下角(0,0)右上角(Screen.width,Screen.height)
Screen.width = Camera.main.pixelWidth;
Screen.height = Camera.main.pixelHeight;
可通過Input.mousePosition獲取屏幕座標
GUI座標:
通過OnGUI()方法繪製UI時使用的座標。
單位像素
屏幕左上角(0,0) 右下角(Screen.width,Screen.height)
創建一個空物體預製體,貼腳本:
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 = 3.5F;
//文本大小
public int fontSize = 30;
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 = fontSize;
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);
}
}
Transform.Translate 在Unity中這是最基礎的一種物體移動的方式之一,物體會按照你給的速度方程移動。Camera.main.WorldToScreenPoint(mTarget) 把物體的世界座標轉換爲屏幕座標。
WorldToScreenPoint:從世界空間到屏幕空間變換位置。屏幕空間以像素定義,屏幕左下爲(0,0),右上是(pixelWidth,pixelHeight),Z的位置是以世界單位衡量的到相機的距離。
ScreenToWorldPoint:從屏幕空間到世界空間的變化位置。屏幕空間以像素定義。屏幕的左下爲(0,0);右上是(pixelWidth,pixelHeight),Z的位置是以世界單位衡量的到相機的距離。
gui座標和屏幕座標的關係:
gui座標:左上(0,0) 右下(Screen.width,Screen.height)
屏幕座標:左下(0,0) 右上(Screen.width,Screen.height)
屏幕座標爲 (x,y)的點,在GUI座標裏爲(x,Screen.height-y)
當銷燬敵人的時候,創建這個預製體,就能實現顯示擊殺文字的效果了。