Answer
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 fixture
s involved in the collision, and subsequently the body
s 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.