问题描述
我正在制作自上而下的2D游戏,我不确定在死后如何在角色上方放置文本.
I am making a top down 2D game, and I am not sure how to place text above a character when then die.
我创建了一个带有空游戏对象的预制件,该对象带有一个附加的GUIText
组件.当我的对象死亡时,我需要在其上方创建一个预制对象.当对象死亡时,将在正确的位置创建预制件,但是文本通常离屏幕很远……为什么这样做?
I created a prefab with an empty game object which has a GUIText
component attached to it. When my object dies I need to create the prefab object above it. When the object dies, the prefab is created in the correct spot, but the text is usually way off of the screen... Why is it doing that?
这是代码:
void destroySelf(){
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
GameObject obj = GameObject.Instantiate(pointsTxt, transform.position / 0.1f, Quaternion.identity) as GameObject;
obj.GetComponent<GUIText>().text = "+" + killPoints.ToString();
Destroy(transform.parent.gameObject);
}
推荐答案
GUIText世界定位在0..1范围内工作. transform.position = Vector3(0,0,0)
等效于屏幕的左下角; transform.position = Vector3(1,1,0)
是屏幕的右上角.
GUIText world positioning works in a 0..1 range. transform.position = Vector3(0,0,0)
is the equivalent of bottom-left corner of the screen; transform.position = Vector3(1,1,0)
is the top-right corner of the screen.
使用WorldToScreenPoint
您有正确的主意;现在您只需要获取0..1范围内的位置值即可:
You've got the right idea using WorldToScreenPoint
; now you just need to get the position values within the 0..1 range:
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
pos.x = pos.x / Screen.width;
pos.y = pos.y / Screen.height;
GameObject obj = GameObject.Instantiate(pointsTxt, pos, Quaternion.identity) as GameObject;
或者,您可以将GUIText的位置保留为Vector3.zero(默认为Instantiate
),并改为更改其pixelOffset
值:
Alternatively, you could leave the GUIText's position as Vector3.zero (default from Instantiate
), and alter its pixelOffset
values instead:
Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
GameObject obj = GameObject.Instantiate(pointsTxt) as GameObject;
GUIText text = obj.GetComponent<GUIText>();
text.pixelOffset.x = pos.x;
text.pixelOffset.y = pos.y;
这篇关于在杀死的角色上方创建GUI文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!