Home > Uncategorized > Objective-C and Chipmunk’s cpSpaceAddCollisionPairFunc

Objective-C and Chipmunk’s cpSpaceAddCollisionPairFunc

April 19th, 2009

I've been writing some really inefficient code in the past couple of hours. Mostly because I didn't know how to call methods on my Objective-C object from a C callback function. If you are using Chipmunk with Cocos2d you might come across the need to have some code respond to certain collisions, say a main character in a game and a pit of spikes. Here is the simple solution:

When you call Chipmunk's collision pair function in your Objective-C object you need to utilize that last parameter:

 
cpSpaceAddCollisionPairFunc(space, 0, 2, &damage, self);
 

In the above line &damage would reference a static C function outside of your Obj-C class and have a signature like this:

 
static int damage(cpShape *a, cpShape *b, cpContact *contacts,
int numContacts, cpFloat normal_coef, void *data)
 

In this C function you would then need to cast the pointer to self back to its object type. For example, the object where I called cpSpaceAddCollisionPairFunc was called GameLayer, thus my callback looks like this:

 
static int damage(cpShape *a, cpShape *b, cpContact *contacts,
int numContacts, cpFloat normal_coef, void *data)
{
	 GameLayer *game = (GameLayer *)data;
    //Calls damageTaken function on Obj-C GameLayer object:
       [game damageTaken];
	return 0;
}
 

Now that I've figured out this little trick I need to go back and get rid of a little of ugly global variables and schedulers. :P

rjett Uncategorized , , , , ,

  1. No comments yet.
  1. No trackbacks yet.