Sensors in Box2D

Box2D has these things called “sensors”. What are they? They are shapes that can be attached to a body with a fixture just like any other, but the crucial difference is they don’t participate in collisions. In other words, something colliding with a sensor will never cause the object containing the sensor to change position, speed, rotation, or acceleration. “So, what’s the point?” you say. The point is you can still cause code to execute when these collisions begin or end, through your contact listener.

What good does that do? Plenty. You can use sensors to determine when any two shapes start or end colliding. You could use sensors to define field-of-vision for enemy units, create a proximity alarm when the player gets too close to laser tripwires or torpedoes, guide a heat-seeking missile, manage fog of war rendering decisions, or help enemies avoid crashing into other enemies and walls.

In my upcoming game Deep Space Demolition Derby, I’m using sensors in a few places. First, there is a big circular sensor surrounding the player:

20140408-015555.jpg

The above picture shows the game in debug mode, where the shapes overlaid on the sprites show the Box2D objects that represent the sprites for physics purposes. I have chosen to represent most of the objects in my game with circles. You can see a small circle around the player, and a small circle around each collectible crystal. This defines their physical extent – when those shapes touch, a collision has happened.

The large circle around the player is a sensor that doesn’t cause collisions, but causes collectible crystals and powerups to appear when you get close enough. Also, when you have a magnet powerup, any crystal that is within that distance will be sucked towards you.

Enemies have sensors to help control their AI. I put a couple of circles to the front left and right of enemies. These are like “vision” areas that help the enemy “sense” what’s in front of it to the right or left sides. When a wall or other enemy or the player overlaps either of those sensors, the enemy turns away to avoid a collision.

In the picture below, the enemy’s sensor has overlapped with the player and so it will turn to avoid a collision:

20140408-020112.jpg

The next picture shows the enemy has turned away and dodged the player:

20140408-020327.jpg

As development continues, I’m sure I’ll find a lot more uses for Box2D’s sensors. I’m excited to continue exploring this cool feature, and excited for the possibilities it has to improve my games.

Leave a Reply

Your email address will not be published. Required fields are marked *