如何将RectTransform(UI面板)转换为屏幕坐标?

Pet*_*ris 1 unity-game-engine

我想确定Unity3D中RectTransform的屏幕坐标。考虑到元素可能已锚定,甚至缩放,该如何完成?

我试图使用RectTransform.GetWorldCorners,然后将每个Vector3转换为屏幕坐标,但是值是错误的。

public Rect GetScreenCoordinates(RectTransform uiElement)
{
    var worldCorners = new Vector3[4];
    uiElement.GetWorldCorners(worldCorners);
    var result = new Rect(
        worldCorners[0].x,
        worldCorners[0].y,
        worldCorners[2].x - worldCorners[0].x,
        worldCorners[2].y - worldCorners[0].y);
    for (int index = 0; index < 4; index++)
        result[index] = Camera.main.WorldToScreenPoint(result[index]);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*ris 5

尽管该帮助说它返回的是世界空间中的坐标,但实际上它们位于屏幕空间中(至少当UI不在世界空间中时)。所以解决方案很简单:

public Rect GetScreenCoordinates(RectTransform uiElement)
{
  var worldCorners = new Vector3[4];
  uiElement.GetWorldCorners(worldCorners);
  var result = new Rect(
                worldCorners[0].x,
                worldCorners[0].y,
                worldCorners[2].x - worldCorners[0].x,
                worldCorners[2].y - worldCorners[0].y);
  return result;
}
Run Code Online (Sandbox Code Playgroud)