How to check the collision / overlap of two Box2d bodies at any time?

How can you check if 2 bodies collide (with 1 Fixture both)?

I know about ContactListener, which starts a method when they start to collide and when they stop. But is there any way to check this at any time? How:

if(body1.overlaps(body2))... 

Additional information, one of which is a sensor. this is in libgdx.

+7
source share
3 answers

You can apply setContactlistner to your world object, e.g.

 world.setContactListener(new ContactListener() { @Override public void beginContact(Contact contact) { if(contact.getfixtureA.getBody().getUserData()=="body1"&& contact.getfixtureB.getBody().getUserData()=="body2") Colliding = true; System.out.println("Contact detected"); } @Override public void endContact(Contact contact) { Colliding = false; System.out.println("Contact removed"); } @Override public void postSolve(Contact arg0, ContactImpulse arg1) { // TODO Auto-generated method stub } @Override public void preSolve(Contact arg0, Manifold arg1) { // TODO Auto-generated method stub } }); 

The beginContact() method will always call whenever any body overlaps or touches another body. You can also get body information from a contact object, for example contact.getFixtureA().getBody().getUserData(); if you want to do something with them. And when they separate from each other. EndContact() will call the method.

Hope this helps.

+5
source

Just check if the contact you are looking for is in your contact list:

 for (ContactEdge ce = body1.getContactList(); ce != null; ce = ce.next) { if (ce.other == body2 && ce.contact.isTouching()) { // Do what you want here break; } } 
+2
source

You can create a variable collision: When equal to 0, the collision is false; When equal to 1, the collision is true,

So:

 if(body1.overlaps(body2)==true) {collision=1} else {collision=0} 
-one
source

All Articles