簡體   English   中英

如何讓 ui 元素指向統一的世界坐標中的 position?

[英]How can i get an ui element to point towards a position that is in world coordinates in unity?

所以我試圖在我的場景中將箭頭指向 position,我想將箭頭旋轉到那個 position。 我試圖將世界 position 變成屏幕 position ,然后從中減去箭頭的 position ,然后將其設置為正確的位置(但我在轉換另一個位置以使其正確旋轉時遇到了一些麻煩) . 該腳本附加到我希望它指向的 object,這是我當前的代碼:

    Vector3 viewportPos = Camera.main.WorldToViewportPoint(transform.position);
    Vector2 worldObjScreenPos = new Vector2(
        (viewportPos.x * canvasRectTrans.sizeDelta.x) - (canvasRectTrans.sizeDelta.x * 0.5f),
        (viewportPos.y * canvasRectTrans.sizeDelta.y) - (canvasRectTrans.sizeDelta.y * 0.5f));

    Vector3 rot = worldObjScreenPos - arrowRectTrans.anchoredPosition;
    arrowRectTrans.rotation = Quaternion.Euler(rot);

但這給了我一些奇怪的結果,箭頭開始瘋狂地旋轉。

如果我理解正確,您希望您的 2D 屏幕空間 UI 指向“朝向”3D 世界空間坐標轉換為屏幕空間 position。

你可能可以簡單地做

var screenPos = Camera.main.WorldToScreenPoint(transform.position);
// In a Screenspace Overlay Canvas this already comes in Screen/pixel space
var arrowPos = arrowRectTrans.position;

// Get the vector pointing from arrow towards the screenPos
// in screen/pixel space
var direction = screenPos - arrowPos;

// Simply assign the transform.up which will rotate the object 
// so that the up will match the direction
arrowRectTrans.up = direction;

這樣,您根本不必處理任何復雜的數學和四元數;)

暫無
暫無

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

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