【问题标题】:How to find a position's coordinates with respect to some anchors on a canvas? (RectTransform.anchoredPosition3D)如何找到关于画布上某些锚点的位置坐标? (RectTransform.anchoredPosition 3D)
【发布时间】:2016-12-17 04:14:48
【问题描述】:

我有一个基于动画的 UI 布局(在 Unity 中),如果您选择一个元素,一些 UI 对象将扭曲到中心,新元素将从中心出现到它们各自的位置。

这些 UI 元素中的每一个都是锚定的,但它们都锚定到不同的锚点。一些在左上角,一些在右上角,一些在左边的中心,等等。
编辑:这是一个手机/平板应用程序,所以它需要适应不同的屏幕尺寸和分辨率,这就是我使用锚点的原因。

我想知道我的画布相对于锚点的中心点。这样我就可以轻松地Vector3.Lerp/Slerp 在我的目标位置(我对锚点的位置)和中心位置之间。

那么我如何找到关于我的锚点的画布中心的正确RectTransform.anchoredPosition3D


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

  • 圆 = 中心
  • 矩形 = UI 元素
  • 三角形 = 锚点
  • 将 UI 元素与 Anchor 匹配的颜色代码

【问题讨论】:

  • 也许使用 Animator 制作动画比脚本动画更容易?
  • @Everts 我的屏幕尺寸不固定,因为它的手机应用。这就是为什么我认为最好使用脚本,因为它适用于所有屏幕尺寸。我可以使用 Animation with Animator 获得同样灵活的结果吗?

标签: unity3d unity5


【解决方案1】:

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

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

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

接下来,我将 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;
}

这样,我可以轻松地在两个位置之间跳跃。

注意:您也可以使用Vector2 代替startPosendPos,并使用rectTransform.anchoredPosition 代替rectTransform.anchoredPosition3D,因为很可能您不需要z-axis为您的用户界面。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-20
    • 2020-06-09
    • 2021-03-13
    • 2011-09-11
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 2018-08-31
    相关资源
    最近更新 更多