Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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. – Byte56 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. – Byte56 Jun 20 '13 at 2:04
up vote 2 down vote accepted

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 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".

share|improve this answer
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

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.