【问题标题】:How can i get an ui element to point towards a position that is in world coordinates in unity?如何让 ui 元素指向统一的世界坐标中的位置?
【发布时间】:2021-12-22 19:33:53
【问题描述】:

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

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

但这给了我一些奇怪的结果,箭头开始疯狂地旋转。

【问题讨论】:

  • 那么箭头默认是向右还是向上?
  • @derHugo 它指向上方

标签: c# unity3d unity-ui


【解决方案1】:

如果我理解正确,您希望您的 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;

这样你就不用处理任何复杂的数学和四元数了;)

【讨论】:

  • 谢谢!完美运行!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 2019-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多