Using Chipmunk for just collision detection

Tip

Here is an important note: if you're going to just detect one of the following, you do not need to use a physics engine for your collision detection, but rather the listed method:

  • For rectangles intersecting rectangles, use CGRectIntersectsRect
  • For points inside rectangles, use CGRectContainsPoint
  • For radius/distance intersection, use ccpDistance

If you're going to be detecting collisions with non-rectangular and noncircular objects, feel free to read on.

Sometimes, all you're doing is sending objects across the screen, or rotating them with your custom actions, and you just want to know when two objects collide, but don't want the bouncing, pushing, and colliding that comes with the entire physics engine. Luckily, we can do that in Chipmunk.

Turning the physics body into a sensor

Sensors, with respect to Chipmunk, are basically bodies that can detect collisions, but pass right through other bodies. These are helpful when you have areas or sections of the screen that trigger certain events, but don't actually cause any physics-based interactions.

For example, if you're making a top-down mini golf game with a physics engine and you want to include ramps, the best way to do this is to set the ramp as a sensor. When the ball and ramp collide, set the gravity in a certain direction.

To make a body a sensor, simply set the sensor variable to true, like this:

[squareBody setSensor:YES];

If you run the game now, you'll notice that the blocks fall right through one another, as well as right through the floor.

And that's it! All you need is the collision handling (in the previous section), and the sensor variable set to true. Any physics body that's a sensor will trigger collision detection events, but not cause any movement or changes to other bodies.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.226.240