Here is some code you can use to get started:
static void eachShape(void *ptr, void* unused)
{
cpShape *shape = (cpShape*) ptr;
Sprite *sprite = shape->data;
if( sprite != nil) {
cpBody *body = shape->body;
if (sprite.tag == kWeaponOffset + 1) { // This is another sprite moving via chipmunk. In this case it's a bullet
[sprite setPosition: cpv( body->p.x, body->p.y)];
[sprite setRotation: (float) CC_RADIANS_TO_DEGREES( -body->a )];
}
else { // This is another sprite moving via moveTo or any other Action
body->p = sprite.position;
cpBodySetAngle(body, -CC_DEGREES_TO_RADIANS(sprite.rotation));
}
}
}
static int weaponCollision(cpShape *a, cpShape *b, cpContact *contacts, int numContacts, cpFloat normal_coef, void *data)
{
NSLog(@"Enemy Weapon Collision e:%f,%f w:%f,%f",a->body->p.x, a->body->p.y,b->body->p.x, b->body->p.y);
GameLayer *game = (GameLayer*) data;
[game weaponCallback:a b:b];
return 0;
}
// Adding Body to weapon.
-(void) addBodyToWeapon: (AtlasSprite *)theSprite
{
int num = 4;
CGPoint verts[] = {
ccp(-(theSprite.contentSize.width/2),-(theSprite.contentSize.height/2)),
ccp(-(theSprite.contentSize.width/2), (theSprite.contentSize.height/2)),
ccp( (theSprite.contentSize.width/2), (theSprite.contentSize.height/2)),
ccp( (theSprite.contentSize.width/2),-(theSprite.contentSize.height/2)),
};
cpBody *body = cpBodyNew(1.0f, cpMomentForPoly(1.0f, num, verts, CGPointZero));
body->p = theSprite.position;
// You don't need to add this line if you are using actions but you need if using chipmunk to move
cpSpaceAddBody(space, body);
cpShape* shape = cpPolyShapeNew(body, num, verts, ccp(theSprite.contentSize.width/2,theSprite.contentSize.height/2));
shape->e = 0.0f; shape->u = 0.0f;
shape->data = theSprite;
shape->collision_type = 4;
cpSpaceAddShape(space, shape);
cpSpaceAddCollisionPairFunc(space, 1, 4, &weaponCollision, self);
}
-(void)weaponCallback:(cpShape*)s b:(cpShape*)b
{
// I do stuff with the enemy and weapon like determine how much damage weapon does to enemy.
}
// Remove chipmunk shape. Remove shape BEFORE removing sprite.
-(void)cleanupShape:(cpShape*)s
{
cpSpaceRemoveShape(space, s);
cpSpaceRemoveBody(space, s->body);
cpBodyFree(s->body);
cpShapeFree(s);
}
Hope this helps get you in the right direction. As mentioned, somebody posted almost the entire solution prior. Make sure you tag your sprites diligently. If anybody sees any issues, let me know. This works for me. I had an issue where my weapon and enemy had same tag and it took a while to debug when I got bad exec upon removal.
-Jim ;)