首页 文章

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

提问于
浏览
3

我有一个GameObject,它从UnityEngine.EventSystems实现IDragHandler和IDropHandler .

在OnDrop中,我想检查,是否已将此对象放在另一个对象的前面 . 我正在使用Physics.Raycast,但在某些情况下它只返回true . 我使用屏幕点光线作为我的光线的方向,这个变换作为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);
         }
 }

我正在使用透视相机 . 当物体从屏幕/摄像机直接放在物体前面时,Physics.Raycast有时会返回true,但“hit”包含这个,而不是它背后的对象 . 有时它会返回false . 这两个结果都不是预期的,这背后有一些对象应该可以用于Raycast .

当对象被放置在摄像机视图的郊区的前方对象中时,Physics.Raycast成功找到了后面的对象 .

调试光线看起来很好,它是从我丢弃的对象中绘制的,向后移动到它应该击中的对象 .

1 回答

  • 1

    临时放置在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块 .

相关问题