Unity 5.6 2D- 如何检查 2 个对撞机是否没有接触任何其他对撞机? [英] Unity 5.6 2D- How can I check if 2 colliders isn't touching any other collider?

查看:35
本文介绍了Unity 5.6 2D- 如何检查 2 个对撞机是否没有接触任何其他对撞机?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Unity 5.6 C# 中,我知道有一种方法可以使用 IsTouching 检查碰撞器是否被任何其他碰撞器触摸.

In Unity 5.6 C#, I know there is a way to check for if a collider is being touched by any other collider by using IsTouching.

但是,我想知道如何将两个对撞机组合在一起(彼此接触),以及如何检查它们是否都在接触彼此之外的任何对撞机.

However, I would like to know how to group two colliders together(that are touching each other), and how to check if they both are touching any collider besides each other.

推荐答案

我会用我在评论中提到的想法来试一试(我觉得只有评论部分很难理解).

I will give it a shot with the idea I mentioned in the comments (I see it is hard to understand with only the comments section).

我会使用碰撞列表并在此处存储任何接触,使用 OnCollisionEnterOnCollisionExit.

I would use a list of collisions and store any touches here, filtering out the "partner" collider using OnCollisionEnter and OnCollisionExit.

因为两者都附加到同一个游戏对象,所以很容易过滤它们:

Since both are attached to the same GameObject it is easy to filter them:

public class Collisions : MonoBehaviour
{
    // Show in the Inspector for debug
    [SerializeField] private List<Collider> colliderList = new List<Collider>();

    public bool IsTouching => colliderList.Count != 0;

    private void Awake ()
    {
        // Make sure list is empty at start
        colliderList.Clear();
    }

    private void OnCollisionEnter(Collision collision)
    {
        // Filter out own collider
        if(collision.gameObject == gameObject) return;

        if(!colliderList.Contains(collision.collider) colliderList.Add(collision.collider);
    }

    private void OnCollisionExit(Collision collision)
    {
        // Filter out own collider
        if(collision.gameObject == gameObject) return;

        if(colliderList.Contains(collision.collider) colliderList.Remove(collision.collider);
    }
}

<小时>

在智能手机上打字,但我希望思路清晰

这篇关于Unity 5.6 2D- 如何检查 2 个对撞机是否没有接触任何其他对撞机?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆