static void
postStepRemove(cpSpace *space, cpShape *shape, void *unused)
{
cpSpaceRemoveShape(space, shape);
cpSpaceRemoveBody(space, shape->body);
cpShapeFree(shape);
cpBodyFree(shape->body);
}
static int
begin(cpArbiter *arb, cpSpace *space, void *data)
{
// Get the cpShapes involved in the collision
// The order will be the same as you defined in the handler definition
// a->collision_type will be BULLET_TYPE and b->collision_type will be MONSTER_TYPE
CP_ARBITER_GET_SHAPES(arb, a, b);
// The macro expands exactly as if you had typed this:
// cpShape *a, *b; cpArbiterGetShapes(arb, &a, &b);
// Add a post step callback to safely remove the body and shape from the space.
// Calling cpSpaceRemove*() directly from a collision handler callback can cause crashes.
cpSpaceAddPostStepCallback(space, (cpPostStepFunc)postStepRemove, b, NULL);
// The object is dead, don’t process the collision further
return 0;
}
#define BULLET_TYPE 1
#define MONSTER_TYPE 2
// Define a collision handler for bullets and monsters
// Kill the monster by removing it’s shape and body from the space as soon as it’s hit by a bullet
cpCollisionHandler *handler = cpSpaceAddCollisionHandler(space, BULLET_TYPE, MONSTER_TYPE);
handler->beginFunc = begin;