Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if two Box2d bodies collision / overlap at any moment?

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

I know about the ContactListener that fires a method when they start colliding and when they stop. But is there a way to check it in any given moment? Like:

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

Additional details, one of them is sensor. this is in libgdx.

like image 371
Lestat Avatar asked Jun 26 '13 09:06

Lestat


2 Answers

You can apply setContactlistner to your world object like

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 will overlap or touch another body.You can also get the information about the body by contact object like contact.getFixtureA().getBody().getUserData(); if you want to do something with them.And when they separate from each other EndContact() method will be called.

Hope This helps.

like image 139
Jagdeep Singh Avatar answered Oct 17 '22 09:10

Jagdeep Singh


Just check if the contact you are looking for is in the 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;
     }
}
like image 29
Martijn Courteaux Avatar answered Oct 17 '22 07:10

Martijn Courteaux