簡體   English   中英

Unity Physics.Raycast似乎沒有正確檢測它擊中的對象

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

我有一個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成功找到了后面的對象。

調試光線看起來很好,它是從我丟棄的對象,向后到它應該擊中的對象。

暫時放置在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塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM