我希望能够与我的游戏对象进行交互,同时使用“排序层”来组织我的精灵。
目前,“排序层”不会影响我的Raycast /对撞机情况,只会改变我的订单的外观。

在我的测试场景中,我有两个精灵:一个背景和一个对象。
两者都有一个2D Box Collider组件。
我的Raycast脚本假设是要检测鼠标悬停在哪个对象上。背景(BG)或位于BG顶部的对象。

只要在检查器中启用了BG对撞机,我的脚本将仅识别BG,即使另一个对象位于我的BG顶部(在视觉上并根据排序层)(Z位置= 0,排序层也是如此)默认值(BG:0,对象1))。
对撞机的大小正确,如果我从BG中禁用或删除了对撞机,我的脚本将很好地检测到另一个对象。
确保在激活我的BG对撞机的同时检测到我的对象的唯一方法是将对象Z的位置更改为我的BG和我的相机之间的位置(介于0和-10之间)

我尝试过了:


这是一个新的2D项目,因此我的相机Projection设置为Orthograph,我的BG和Object使用Sprite Renderer,并且使用2D Collider
来回更改“层顺序”,包括负数。
添加前景(和背景)“排序图层”
(这两个选项仅具有视觉效果,并不影响Raycast的输出)
更改层次结构中的位置。
删除并重新添加对撞机。 (!)我观察到我最后添加的2D Box对撞机将始终位于其他所有对撞机之后。我现在可以使用此功能。但是随着项目的扩大,将来会成为一个问题。


我希望能够在2D点击冒险中与物品和门等互动(鼠标悬停的点击和反应)。如果不是使用2D Raycast存档,我将很高兴知道在这种情况下可以使用的适当技术。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class RayCast : MonoBehaviour
{
    [SerializeField] private Vector2 mousePosWorld2D;
    RaycastHit2D hit;

    void Update()
    {
        mousePosWorld2D = (Vector2)Camera.main.ScreenToWorldPoint(Input.mousePosition);

        hit = Physics2D.Raycast(mousePosWorld2D, Vector2.zero);
        if (hit.collider)
        {
            Debug.Log("Found collider: " + hit.collider.name);
        }
        else
        {
            Debug.Log("No collider found.");
        }
    }
}


我希望“排序图层”或“图层中的顺序”会对我的Raycast产生影响,而更改Z位置却无济于事。但这是另一回事。排序层仅具有视觉效果,将“对象”移近相机(Z位置)有助于检测正确的对撞机。

我该如何解决这个问题?

最佳答案

您是否尝试过Unity官方文档中的脚本?
https://docs.unity3d.com/ScriptReference/Physics.Raycast.html

using UnityEngine;

// C# example.

public class ExampleClass : MonoBehaviour
{
    void Update()
    {
        // Bit shift the index of the layer (8) to get a bit mask
        int layerMask = 1 << 8;

        // This would cast rays only against colliders in layer 8.
        // But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
        layerMask = ~layerMask;

        RaycastHit hit;
        // Does the ray intersect any objects excluding the player layer
        if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
            Debug.Log("Did Hit");
        }
        else
        {
            Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
            Debug.Log("Did not Hit");
        }
    }
}

10-08 05:42