所以我試圖讓一個箭頭指向我場景中的一個位置,我想將箭頭旋轉到那個位置。我試圖將世界位置變成螢屏位置,然后從中減去箭頭的位置,然后設定旋轉,但是我在轉換旋轉以使其正確時遇到了一些麻煩(或者我在另一個地方做錯了) . 該腳本附加到我希望它指向的物件,這是我當前的代碼:
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);
但這給了我一些奇怪的結果,箭頭開始像瘋了一樣旋轉。
uj5u.com熱心網友回復:
如果我理解正確,您希望您的 2D 螢屏空間 UI 指向“朝向”轉換為螢屏空間位置的 3D 世界空間坐標。
你可以簡單地做
// First of all what you want is not the viewport but screen(=pixel)space
// In general if this is happening more often you should store the Camera.main as it is quite expensive
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;
這樣你就不必處理任何復雜的數學和四元數;)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/392537.html
下一篇:如何在柏林噪聲上實作偏移?
