简体   繁体   English

如何从球体向画布中的 ui 元素进行光线投射

[英]How do I raycast from a sphere to an ui element in the canvas

I would like to Raycast from the center of Sphere GameObject to find the text/image element being hit by the ray.我想从 Sphere GameObject 的中心进行 Raycast 以找到被光线击中的文本/图像元素。 I'm using Physics.RaycastAll to detect the UI element being hit.我正在使用 Physics.RaycastAll 来检测被击中的 UI 元素。 Following is my code.以下是我的代码。

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

I have added BoxCoilloider to the canvas.我已将 BoxCoilloider 添加到画布上。 Unfortunately, hits.Length always returns 0. am I missing something?不幸的是, hits.Length总是返回 0。我错过了什么吗? How do I ray cast from the sphere to the ui element in the canvas to check if it has collided?如何从球体向画布中的 ui 元素投射光线以检查它是否发生碰撞?

I think you have to use the EventSystem if you want to check against UI elements.如果您想检查 UI 元素,我认为您必须使用EventSystem

Try something like this:尝试这样的事情:

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

You can calculate the screen position from your spheres world position using Camera.WorldToScreenPoint .您可以使用Camera.WorldToScreenPoint从球体世界位置计算屏幕位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM