【问题标题】:How do I raycast from a sphere to an ui element in the canvas如何从球体光线投射到画布中的 ui 元素
【发布时间】:2020-05-23 09:01:09
【问题描述】:

我想从 Sphere GameObject 的中心进行射线投射,以找到被射线击中的文本/图像元素。我正在使用 Physics.RaycastAll 来检测被击中的 UI 元素。以下是我的代码。

public class RaycastUI : MonoBehaviour
{

    public GameObject Sphere;

    private Vector3 _origin;
    private Vector3 _direction;

    void Update()
    {
        RaycastHit[] hits;

        // get the origin and direction
        _origin = Sphere.transform.position;
        _direction = Sphere.transform.forward;

        //raycast all
        hits = Physics.RaycastAll(_origin, _direction, 100.0F);

        // retrieve the names of the element that are hit by the sphere.
        for (int i = 0; i < hits.Length; i++) {
            RaycastHit hit  = hits[i];
            Debug.Log(hit.collider.name);
        }
    }
}

我已将 BoxCoilloider 添加到画布中。不幸的是,hits.Length 总是返回 0。我错过了什么吗?如何从球体投射到画布中的 ui 元素以检查它是否发生碰撞?

【问题讨论】:

  • 您可能需要将它放在可以用作光线投射目标的透明图像上
  • 你的意思是我应该把我的按钮放在透明图像中吗?
  • 不,按钮可以有图像,但是纯文本没有。

标签: c# unity3d user-interface virtual-reality raycasting


【解决方案1】:

如果您想检查 UI 元素,我认为您必须使用 EventSystem

试试这样的:

private void GetUIObjectsOfPosition(Vector2 screenPosition)
{
    var eventDataCurrentPosition = new PointerEventData(EventSystem.current);
    eventDataCurrentPosition.position = screenPosition;

    var results = new List<RaycastResult>();
    EventSystem.current.RaycastAll(eventDataCurrentPosition, results);

    foreach (var result in results) {
        Debug.Log(result.gameObject.name);
    }               
}

您可以使用 Camera.WorldToScreenPoint 从您的球体世界位置计算屏幕位置。

【讨论】:

  • 它现在可以工作,但它只检测面板而不是面板中的 UI 元素:(
  • 我有一个与按钮重叠的面板,因此它阻止了按钮接收点击。是否可以将按钮向前移动以使面板不隐藏按钮?
  • 您可以尝试使用组件的Raycast Target 属性。还要检查你的Graphic Raycaster (docs.unity3d.com/Manual/script-GraphicRaycaster.html)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多