I create a ship and some comets. The ship is created in the init method like so:
Code:
_player = [[[HopperShip alloc] initWithSpriteFrameName:@"SpaceFlier_sm_1.png" maxHp:50 healthBarType:HealthBarTypeGreen] autorelease];
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(_player.position.x/PTM_RATIO, _player.position.y/PTM_RATIO);
shipBody = world->CreateBody(&bodyDef);
bodyDef.userData = _player;
b2PolygonShape shape;
shape.SetAsBox(_player.contentSize.width/2/PTM_RATIO, _player.contentSize.height/2/PTM_RATIO);
b2FixtureDef fixtureDef;
fixtureDef.shape = &shape;
fixtureDef.density = 0.0;
fixtureDef.friction = 0.5;
fixtureDef.restitution = 0.5;
shipBody->CreateFixture(&fixtureDef);
This code creates the sprite & its respective shipBody. I added the bodyDef.userData = _player as you can see.
Then I create comets like this:
Code:
target = [WeakAndFastShipTarget target];
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(target.position.x/PTM_RATIO, target.position.y/PTM_RATIO);
cometBody = world->CreateBody(&bodyDef);
bodyDef.userData = target;
b2PolygonShape shape;
shape.SetAsBox(target.contentSize.width/2/PTM_RATIO, target.contentSize.height/2/PTM_RATIO);
b2FixtureDef fixtureDef;
fixtureDef.shape = &shape;
fixtureDef.density = 0.0;
fixtureDef.friction = 0.5;
fixtureDef.restitution = 0.5;
cometBody->CreateFixture(&fixtureDef);
Again I set it to a reference called cometBody this time & set its bodyDef.userData = target
I added the box2d code later because I realized I needed it for better collision detection. I already have a method that removes the comet sprites once they exit the screen if they are not destroyed by the ship. Now I need to remove the corresponding b2body. I have a method that passes the CCNode, a comet CCSprite object, in order to remove that sprite and clean up. How do I get the associated b2body from that sprite?