簡體   English   中英

查找 Unity UI 元素的世界空間坐標

[英]Finding World Space Coordinates of a Unity UI Element

因此,根據 Unity 文檔RectTransform.anchoredPosition將返回 UI 元素的屏幕坐標,如果錨點在 RectTransform 的樞軸點處接觸。 但是,如果它們分開(在我的情況下位於矩形的角落),它們將為您提供錨點相對於樞軸點的位置。 這很好,除非您想通過多種分辨率保持 UI 對象的適當尺寸,並同時根據該位置定位不同的對象。

讓我們分解一下。 我有對象 1 和對象 2。 object1 位於 (322.5, -600) 並且當錨點在對象 anchoredPosition 的中心(樞軸)處相遇時,就返回該位置,而 object2 的位置恰到好處。 另一方面,一旦我將錨點放置在 object1 anchoredPosition 的 4 個角上,就會返回 (45.6, -21)。 那只是不好。 我什至嘗試使用Transform.positionCamera.WorldToScreenPoint() ,但這對我實現目標的作用Camera.WorldToScreenPoint()

我希望你能幫我找到一種方法來獲得這個對象的實際屏幕坐標。 如果有人對此主題有任何見解,將不勝感激。

注意:我已經嘗試使用 RectTranfrom.rect.center 並且它返回 (0, 0)

我還研究了RectTransformUtility並且那些輔助函數已經完成了所有的深蹲。

anchoredPosition 返回“此 RectTransform 的樞軸相對於錨參考點的位置。” 它與屏幕坐標或世界空間無關。

如果您正在 Unity 中查找 UI 元素的屏幕坐標,您可以使用rectTransform.TransformPointrectTransform.GetWorldCorners來獲取您在世界空間中需要的任何Vector3 無論您決定使用哪個,您都可以將它們傳遞給Camera.WorldToScreenPoint()

如果您卡住並需要將您自己的轉換從視圖空間滾動到世界空間,這里將簡要介紹如何找到 UI 元素的世界空間坐標。

如果說你需要的不僅僅是 rectTransform.TransformPoint 或者想知道它是如何工作的,這可能是有益的。

好的,所以您想從 [-1, 1] 范圍內的規范化 UI 坐標進行轉換,並將它們反投影回世界空間坐標。

要做到這一點,你可以使用像 Camera.main.ScreenToWorldPoint 或 Camera.main.ViewportToWorldPoint 之類的東西,或者甚至 rectTransform.position 如果你是一個缺乏者。

這是僅使用相機的投影矩陣來完成的方法。

/// <summary>
/// Get the world position of an anchor/normalised device coordinate in the range [-1, 1]
/// </summary>
private Vector3 GetAnchor(Vector2 ndcSpace)
{
    Vector3 worldPosition;

    Vector4 viewSpace = new Vector4(ndcSpace.x, ndcSpace.y, 1.0f, 1.0f);

    // Transform to projection coordinate.
    Vector4 projectionToWorld = (_mainCamera.projectionMatrix.inverse * viewSpace);

    // Perspective divide.
    projectionToWorld /= projectionToWorld.w;

    // Z-component is backwards in Unity.
    projectionToWorld.z = -projectionToWorld.z;

    // Transform from camera space to world space.
    worldPosition = _mainCamera.transform.position + _mainCamera.transform.TransformVector(projectionToWorld);

    return worldPosition;
}

我發現您可以將坐標乘以相機尺寸的 2 倍並將其除以屏幕高度。

我在全高清屏幕 (1920 x 1080) 上放置了一個面板 (0, 1080),相機尺寸為 7。因此世界空間中的 Y 坐標將為1080 * 7 * 2 / 1080 = 14 -> (0, 14).

ScreenToWorldPoint 將畫布位置轉換為世界位置:

Camera.main.ScreenToWorldPoint(transform.position)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM