找到画布的左上角位置

Dav*_*vid 4 c# position canvas unity-game-engine

获取对象的位置:

Vector3 mainCanvasPosition = mainCanvas.GetComponent<RectTransform>().position;
Run Code Online (Sandbox Code Playgroud)

但它返回对象中心的位置.

我怎样才能获得左上角的位置? 在此输入图像描述

Cen*_*abi 5

mainCanvas.GetComponent().rect.xMin为画布空间中的画布提供最小x位置,而不是世界空间.因此,如果将xMin添加到画布的x位置,则在世界空间中获得画布的最小x位置.同样的y.

所以;

float minX = mainCanvas.GetComponent<RectTransform>().position.x + mainCanvas.GetComponent<RectTransform>().rect.xMin;
float maxY = mainCanvas.GetComponent<RectTransform>().position.y + mainCanvas.GetComponent<RectTransform>().rect.yMax;
float z = mainCanvas.GetComponent<RectTransform>().position.z;

Vector3 topLeft = new Vector3(minX, maxY, z);
Run Code Online (Sandbox Code Playgroud)

会给你画布的左上角

编辑:https://docs.unity3d.com/ScriptReference/RectTransform-rect.html

如果你看看Unity的参考,你应该看到RectTransform.rect在本地空间,而不是在世界空间

  • 我的互联网出现问题,无法回复.至于我的解决方案,你可以使用`TransformPoint`将本地空间转换为世界空间,这样就不会有任何问题.实际上,我是通过场景视图测试我的,所以我没有注意到. (2认同)