Unity 5.6 2D- How can I check if 2 colliders isn't touching any other collider?

╄→尐↘猪︶ㄣ 提交于 2020-02-08 10:47:59

问题


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.


回答1:


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).

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);
    }
}

Typed on smartphone but I hope the idea gets clear



来源:https://stackoverflow.com/questions/59439562/unity-5-6-2d-how-can-i-check-if-2-colliders-isnt-touching-any-other-collider

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!