问题
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