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

查看:80
本文介绍了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).

我将使用碰撞列表并在此处存储所有触摸,并使用 OnCollisionEnter OnCollisionExit

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

由于两个都附加到同一个GameObject上,因此很容易过滤它们:

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天全站免登陆