Reputation: 1072
I've realized that CCPhysicsSprite is different in a few ways from CCSprite. For example, you must set the body before you set the position of the sprite. I believe it is one of these differences that is causing an EXC_BAD_ACCESS error when I try destroying the body. I call the scheduleSprite method in the update method.
-(void)scheduleSprite {
if ([testSprite physicsSprite].b2Body != NULL) {
b2Vec2 force = b2Vec2(-5, 10.0 * [testSprite physicsSprite].b2Body->GetMass());
[testSprite physicsSprite].b2Body->ApplyForce(force, [testSprite physicsSprite].b2Body->GetWorldCenter() );
if ([testSprite physicsSprite].position.x < 0) {
world->DestroyBody([testSprite physicsSprite].b2Body);
[testSprite physicsSprite].b2Body = NULL;
}
}
}
I get an EXC_BAD_ACCESS pointing to line
b2Vec2 pos = _b2Body->GetPosition();
in the
-(CGAffineTransform) nodeToParentTransform
method, within the class
CCPhysicsSprite.mm
Thanks.
Upvotes: 0
Views: 609
Reputation: 666
- (void) killBody:(cpBody*)body
{
cpBodyEachShape_b(body, ^(cpShape *shape) {
cpSpaceRemoveShape( _space, shape );
cpShapeFree(shape);
});
cpSpaceRemoveBody( _space, body );
cpBodyFree(body);//edited to include this line
CCPhysicsSprite* sprite = (__bridge CCPhysicsSprite*) body->data;
[sprite removeFromParentAndCleanup:true];
}
I was getting the same thing, the method above seemed to fix it. First, remove the shapes attached to the body from the space. I'm using _space as a instance variable pointing to a cpSpace object. Next, remove the body from the space. Finally, remove the sprite from the parent.
When I make a CCPhysicsSprite object, I connect its body to the sprite using body->data. You can see that in the method above.
If you are starting with a CCPhysicsSprite object, you would first get the cpBody object from the sprite, then remove the body and shape as shown above.
Upvotes: 0
Reputation: 16526
Despite you destroyed the body
, the sprite
will keep doing its stuff, so you may remove the sprite from its parent also, something like.-
if ([testSprite physicsSprite].position.x < 0) {
world->DestroyBody([testSprite physicsSprite].b2Body);
[[testSprite physicsSprite] removeFromParentAndCleanup:YES];
}
Upvotes: 1