3
\$\begingroup\$

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?

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – MichaelHouse Jun 20 '13 at 1:18
  • \$\begingroup\$ 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? \$\endgroup\$ – Matthew James Davis Jun 20 '13 at 1:47
  • \$\begingroup\$ Sure a physics engine has optimizations, but so can you. \$\endgroup\$ – MichaelHouse Jun 20 '13 at 2:04
3
\$\begingroup\$

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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