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\$
3
  • \$\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\$
    – House
    Jun 20, 2013 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\$ Jun 20, 2013 at 1:47
  • \$\begingroup\$ Sure a physics engine has optimizations, but so can you. \$\endgroup\$
    – House
    Jun 20, 2013 at 2:04

1 Answer 1

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

\$\endgroup\$
1
  • \$\begingroup\$ Thanks so much, this worked great. Please note the small change I made to your answer for any future readers. \$\endgroup\$ Jun 20, 2013 at 4:01

You must log in to answer this question.

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