I'm using LibGDX with Box2D and I've two bodies. I just need to know that they have collided.

So, I just need a boolean output.


if (bodyA.collision(bodyB) == true) {
   // Do something

How can I do this?

If it is too complicated, can I detect if two PolygonShape intersect?


1 Answer 1



What you are looking for is called a Collision Callback. There is a great tutorial written by iforce2d on the topic, so I'll just give the key details here.

The strategy in Box2d is to subclass the ContactListener class and define the appropriate methods. For example, you could create a subclass called MyContactListener, you would define the method MyContactListener:beginContact. Then, in your initialization, assign an instance of your MyContactListener class to your b2World using the function b2World:setContactListener. Once this is set up, the code inside your beginContact function will be called each and every time two bodies collide! (provided you do not have any contact filters set up)

In the beginContact function, you are given access to the contact object, from which you can query the fixtures involved in the collision, and subsequently the bodys involved.

General Advice

I see from the way you phrased your question that you want your code to poll the game state to see if you should do something. This is generally considered poor practice, and this particular example is a great way to start changing your thinking!

What box2d is doing, and what you should strive to do as well, is to create triggers/events/callbacks so that when something interesting happens (e.g. a collision) the game will change what it needs to right then and there. It's the difference between the kids in the back seat asking 23,139 times: "Are we there yet?" and patiently waiting for their parent to say "We've arrived!" just 1 time.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .