我怎样才能让 ui 元素指向统一世界坐标中的位置?

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

所以我试图让箭头指向场景中的某个位置,我想将箭头旋转到该位置。我试图将世界位置变成屏幕位置,然后从中减去箭头的位置,然后设置旋转,但我在转换旋转以使其正确时遇到了一些麻烦(或者我在另一个地方做错了) .该脚本附加到我希望它指向的对象,这是我当前的代码:

    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 屏幕space UI 指向“朝向”3D 世界 space 坐标转换为屏幕 space 位置。

你可以简单地做

// 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;

这样您就完全不必处理任何复杂的数学和四元数 ;)