Unity Physics.Raycast 似乎没有正确检测到它击中的对象

Unity Physics.Raycast does not seem to properly detect object it hit

我有一个 GameObject 实现了 UnityEngine.EventSystems 的 IDragHandler 和 IDropHandler。

在 OnDrop 中,我想检查,这个对象是否被放在另一个对象前面。我正在使用 Physics.Raycast,但在某些情况下它仅 returns 正确。我使用屏幕点到光线作为光线的方向,并将此变换作为 Raycast 光线的原点。

我的代码:

 public void OnDrop(PointerEventData eventData)
 {
         var screenRay = Camera.main.ScreenPointToRay(new Vector3(eventData.position.x, eventData.position.y, 0.0f));
         var thisToObjectBehind = new Ray(transform.position, screenRay.direction);
         Debug.DrawRay(thisToObjectBehind.origin, thisToObjectBehind.direction, Color.yellow, 20.0f, false);
         RaycastHit hit;
         if (Physics.Raycast(thisToObjectBehind, out hit))
         {
             Debug.LogFormat("Dropped in front of {0}!", hit.transform);
         }
 }

我使用的是透视相机。当对象从 screen/camera 直接放在对象前面时,Physics.Raycast 有时 returns 为真,但 "hit" 包含这个,而不是后面的对象。有时它 returns 错误。 None 这两个结果是预期的,这背后有对象应该可以进行 Raycast。

当物体落在摄像机视野外围的物体前面时,Physics.Raycast成功找到后面的物体。

Debug 射线看起来不错,它是从我放下的物体绘制的,向后返回到它应该击中的物体。

暂时将掉落的对象放置在 IgnoreRaycast 层中解决了我的问题。这也意味着我可以跳过将光线的原点设置为 transform.position.

    public void OnDrop(PointerEventData eventData)
    {
        // Save the current layer the dropped object is in,
        // and then temporarily place the object in the IgnoreRaycast layer to avoid hitting self with Raycast.
        int oldLayer = gameObject.layer;
        gameObject.layer = 2;

        var screenRay = Camera.main.ScreenPointToRay(new Vector3(eventData.position.x, eventData.position.y, 0.0f));
        RaycastHit hit;
        if (Physics.Raycast(screenRay, out hit))
        {
            Debug.LogFormat("Dropped in front of {0}!", hit.transform);
        }

        // Reset the object's layer to the layer it was in before the drop.
        gameObject.layer = oldLayer;
    }

编辑:由于性能原因,从代码片段中删除了 try/finally 个块。