I'm trying to get contacts through the collider but I'm only getting a contact with one object, although the collider in the unit shows two contacts with two objects. As I noted in the tests, GetContacts can only return contacts with one object. All this is about OnCollisionStay2D
I need GetContacts to return all contacts with all objects and how it shows in the inspector
Code is just testing
OnCollisionStay2D
is called once for each colliding object individually!
If it collides with two objects but each of those has only one single contact of course this will only print 1
But in total it will have two contacts because it is two different collision.collider
it is colliding with and the method is called for (you should get the message logged two times per physics frame (FixedUpdate
))
I need GetContacts to return all contacts with all objects
well it doesn't.
But you could of course store all the individual colliding objects and their according contacts and then return them all like e.g.
private readonly Dictionary<Collider2D, ContactPoint2D[]> allContactsByCollider = new ();
private void OnCollisionStay2D(Collision2D collision)
{
var contacts = new ContactPoint2D[collision.contactCount];
if(collision.contactCount > 0)
{
collision.GetContacts(contacts);
}
allContactsByCollider[collision.collider] = contacts;
}
private void OnCollisionExit2D(Collision2D collision)
{
allContactsByCollider.Remove(collision.collider);
}
public IEnumerable<ContactPoint2D> GetAllContacts()
{
foreach(var kvp in allContactsByCollider)
{
foreach(var contact in kvp.Value)
{
yield return contact;
}
}
}