Chipmunk and Cocos2d
In Short: With the right methods set up anytime you add a sprite to the data part of a cpShape than it will draw the sprite and set its rotation on every frame.
In long: Lets say your starting from a new cocos2d project that compiles. First you’re going to want to set up the chipmunk engine, I have a nice little helper method for this, that’s well commented.
- (void) initChipmunk{
// start chipumnk
// create the space for the bodies
// and set the hash to a rough estimate of how many shapes there could be
// set gravity, make the physics run loop
// make a bounding box the size of the screen
cpInitChipmunk();
space = cpSpaceNew();
cpSpaceResizeStaticHash(space, 4, 20);
cpSpaceResizeActiveHash(space, 50.0, 500);
space->gravity = cpv(0, -200);
staticBody = cpBodyNew(INFINITY, INFINITY);
[self schedule: @selector(step:)];
// Game specific logic here.
}
Next I would write the code for the physics run loop, luckily Riq has made this for me, and the less code I’ve wrote the better
-(void) step: (ccTime) delta {
int steps = 2;
cpFloat dt = delta/(cpFloat)steps;
for(int i=0; iactiveShapes, &eachShape, nil);
cpSpaceHashEach(space->staticShapes, &eachShape, nil);
}
This will keep the chipmunk engine working in realtime (because if frames get skipped than the dt will go up) we then give cpSpaceHashEach a method pointer (in the case &eachShape) to have this method called on every static/active object in the space. This has to be a C method, so lets look at that
static void eachShape(void *ptr, void* unused){
cpShape *shape = (cpShape*) ptr;
Sprite *sprite = shape->data;
if( sprite ) {
cpBody *body = shape->body;
[sprite setPosition: cpv( body->p.x, body->p.y)];
[sprite setRotation: RADIANS_TO_DEGREES( -body->a )];
}
}
This is a great piece of code in my opinion, again, Riqs work. we make a shape from the void pointer then check if it has a sprite in its data, if so, set the position and rotation in accordance to the chupmunk body. Perfect.
That’s the longer explaination of how Chipmunk connects to Cocos2d.
I really advise checking out both thrown and grabbed as they have some useful helper methods for making shapes quickly and throwing them into your scene that I was tempted to add to this post.