如何在 canvas 上找到相对于某些锚点的位置坐标? (RectTransform.anchoredPosition 3D)

How to find a position's coordinates with respect to some anchors on a canvas? (RectTransform.anchoredPosition3D)

我有一个基于动画的 UI 布局(在 Unity 中),如果你 select 一个元素,一些 UI 对象会扭曲到中心,新元素会出现从中心出来到各自的位置。

每个 UI 元素都已锚定,但它们都锚定到不同的 anchor-point。有的在左上角,有的在右上角,有的在左中,等等。
编辑:这是一个移动 phone/tablet 应用程序,因此它需要适应不同的屏幕尺寸和分辨率,所以这就是我使用锚点的原因。

我想知道我的 Canvas 相对于锚点的中心点。这样我就可以很容易地 Vector3.Lerp/Slerp 在我的目标位置(这是我对锚点的看法)和中心位置之间。

那么如何找到我的 canvas 中心的正确 RectTransform.anchoredPosition3D 相对于我的锚?


这是一个可能设置的图示,我想在 UI 元素的 RectTransform.anchoredPosition3D 之间 Vector3.Lerp中心的 RectTransform.anchoredPosition3D.

首先,我使用锚将 Unity 编辑器中的 UI 元素定位到正确的位置。

我为每个 UI 元素都有一个控制器,在 Start() 上我可以将它们的 UI 元素的 RectTranform anchoredPosition3D 存储为它的 endPosition,这是我在编辑器里设置的。

然后通过将 RectTransform.localPosition 设置为(例如)Vector3.zero 将 UI 元素移动到其 startPosition,这将是 [=] 的中心48=]。这样,我就可以移动它而无需考虑锚点。

接下来,我将 UI 元素的 RectTranform anchoredPosition3D(现在,在翻译之后,相对于其锚点具有正确的坐标)存储在 startPosition 中。

在代码中它看起来像这样:

Vector3 startPos, endPos;
void Start() {
    rectTransform = this.gameObject.GetComponent<RectTransform> ();

    /* endPos will store the position, that I have set in the editor */
    endPos = rectTransform.anchoredPosition3D;

    /* now I translate the UI element to the center of the Canvas (locally -> 0,0,0) */
    rectTransform.localPosition = Vector3.zero;

    /* I store this position in startPos */
    startPos = rectTransform.anchoredPosition3D;
}

这样,我可以轻松地在两个位置之间进行 Lerp。

注:你也可以用Vector2代替startPosendPos,用rectTransform.anchoredPosition代替rectTransform.anchoredPosition3D,因为您的 UI.

很可能不需要 z-axis

警告: 如果您在 Awake() 中使用上述代码,那么它将 不能 可靠地工作!它在某些情况下有效,但在其他情况下无效,因为不会正确计算 startPos。