Hi there.
I’ve got a question regarding Rigidbody2D.Distance: how can I tell if a rigidbody is actually overlapped with a a collider or just standing over it?
I prepared a small test case:
- Ground: The blue square. Has a box collider.
- DynamicObject: The green square. Has box collider and a rigidbody2D.
- Blocker: The red square. Has a box collider.
DynamicObject has the following script attached to debug the distance to its contacts:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DebugContacts : MonoBehaviour
{
public Rigidbody2D PlayerRigidbody;
private void OnGUI()
{
GUI.Label(new Rect(0f, 0f, 200f, 30f), "DynamicObject contacts:");
List<ContactPoint2D> contacts = new List<ContactPoint2D>();
int contactsCount = PlayerRigidbody.GetContacts(contacts);
if (contactsCount == 0)
{
GUI.Label(new Rect(0f, 15f, 200f, 30f), "\t- NO CONTACTS -");
}
else
{
HashSet<Collider2D> colliders = new HashSet<Collider2D>();
for (int contactIndex = 0; contactIndex < contactsCount; ++contactIndex)
{
colliders.Add(contacts[contactIndex].collider);
}
int colliderIndex = 0;
foreach(Collider2D collider in colliders)
{
ColliderDistance2D colliderDistance = PlayerRigidbody.Distance(collider);
GUI.Label(new Rect(0f, 15f * (1 + 3 * colliderIndex), 500f, 15f * (2 + 3 * colliderIndex)), $"\t* {collider.gameObject.name}");
GUI.Label(new Rect(0f, 15f * (2 + 3 * colliderIndex), 500f, 15f * (3 + 3 * colliderIndex)), $"\t\t* Is overlapped: {colliderDistance.isOverlapped}");
GUI.Label(new Rect(0f, 15f * (3 + 3 * colliderIndex), 500f, 15f * (4 + 3 * colliderIndex)), $"\t\t* Distance: {colliderDistance.distance}");
++colliderIndex;
}
}
}
}
DynamicObject is suspended over Ground and when it falls I get the result showcased in the previous image. As you can see, it’s reported to be overlapped. If I sandwich DynamicObject between Ground and Blocker I get this result;
As expected DynamicObject is again overlapped with Ground.
Is there a way to tell these two cases appart besides picking some arbitrary Distance threshold to decide whether we’re over the Ground or overlapped with it?
Thanks!