# Using Box2D for range detection?

I have two entities. One has a sword, one has a bow and arrow. When the bow entity is 100 units away, he needs to begin attacking. Likewise, when the sword entity is 10 units away, he needs to begin attacking.

My idea is to create an actual physical body for collision detection and a range body (or fixture?) for range detection. However, I don't want the range body to start pushing and affecting other entities. I simply want to detect when one entity's range body collides with another entity's physical body.

Is this the right thing to do and how can I do this with Box2D?

• Why not just use the distance between the two objects for a range? Otherwise you'll need to add some filtering to your physics as well as some custom collision response code. – MichaelHouse Jun 20 '13 at 1:18
• In this case, wouldn't I need to compute the distance between each entity against every other entity at every timestep, i.e. exponential? I imagine the physics engine, though overkill, has optimizations to reduce this complexity? – Matthew James Davis Jun 20 '13 at 1:47
• Sure a physics engine has optimizations, but so can you. – MichaelHouse Jun 20 '13 at 2:04

You can utilize Box2D sensors (or contact listener) for this. Setting one up is fairly simple, and a tutorial can be found here. The basic code (from the link):

var listener = new Box2D.Dynamics.b2ContactListener;
listener.BeginContact = function(contact) {
// console.log(contact.GetFixtureA().GetBody().GetUserData());
}
listener.EndContact = function(contact) {
// console.log(contact.GetFixtureA().GetBody().GetUserData());
}
this.world.SetContactListener(listener);


This listener is where you'll set up your response to your objects getting near each other.

You can read a little about them in the official Box2D manual, under section "6.3 Sensors".

• Thanks so much, this worked great. Please note the small change I made to your answer for any future readers. – Matthew James Davis Jun 20 '13 at 4:01