好的,无论屏幕大小如何,您都必须使用与 Unity 的绝对坐标系不同的坐标系。 Unity 的模型之一是 View。视图是左上角的坐标 0,0,右下角的坐标 1,1。创建一个基本的 Rect 来处理它,如下所示。
using UnityEngine;
namespace SeaRisen.nGUI
{
public class RectAnchored
{
public float x, y, width, height;
public RectAnchored(float x, float y, float width, float height)
{
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
public static implicit operator Rect(RectAnchored r)
{
return new Rect
{
x = r.x * Screen.width,
y = r.y * Screen.height,
width = r.width * Screen.width,
height = r.height * Screen.height
};
}
}
}
在这里,我们采用普通的 Rect 浮点数、x,y 坐标以及宽度和高度。但这些都在值 [0..1] 中。我没有夹住它,所以如果需要的话,它可以在屏幕上和屏幕外进行补间。
以下是一个简单的脚本,它在屏幕右下角创建一个按钮,并随着屏幕的增大或缩小而调整大小。
void MoveMe()
{
RaycastHit hit;
if (Physics.Raycast(transform.position, -Vector3.up, out hit, float.MaxValue)
|| Physics.Raycast(transform.position, Vector3.up, out hit, float.MaxValue))
transform.position = hit.point + Vector3.up * 2;
}
void OnGUI()
{
if (GUI.Button(new RectAnchored(.9f, .9f, .1f, .1f), "Fix me"))
{
MoveMe();
}
}
X 向右为 0.9,Y 距离顶部为 0.9,宽度和高度为 0.1,因此按钮的高度和宽度为屏幕的 1/10,位于屏幕底部的 1/10屏幕。
由于每帧(或左右)都会渲染 OnGUI,因此按钮 rect 会随着屏幕大小自动更新。如果您使用 Update() 来渲染窗口,那么在典型的 UI 中也是如此。
我希望这能解释我所说的绝对坐标之间的区别。在 640x480 中设置前面的示例(使用绝对值),它会类似于 new Rect(576, 432, 64, 48) 并且不会缩放。通过使用new RectAnchored(.9f, .9f, .1f, .1f) 并根据屏幕大小将其渲染到 UI 空间中,然后自动缩放。