I just recently started messing with cocos2d's Box2D integration, while most of the process has been simple and straight forward, I keep running into a EXC_BAD_ACCESS error when using a CCPhysicsSprite (CCSprite subclass that integrates a b2body with the sprite). The code I'm using is:
- (void)spawnBallAtPoint:(CGPoint)point
{
count++;
CCPhysicsSprite *sprite = [CCPhysicsSprite spriteWithFile:@"ball.png" rect:CGRectMake(0, 0, 52, 52)];
sprite.position = point;
[self addChild:sprite];
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(point.x / PTM_RATIO, point.y / PTM_RATIO);
bodyDef.userData = sprite;
b2Body *body = world->CreateBody(&bodyDef);
b2CircleShape circleShape;
circleShape.m_radius = (26.0 / PTM_RATIO);
b2FixtureDef fixtureDef;
fixtureDef.shape = &circleShape;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.2f;
fixtureDef.restitution = 0.8f;
body->CreateFixture(&fixtureDef);
sprite.b2Body = body;
}
This code triggers an EXC_BAD_ACCESS, I know it's the CCPhysicsSprite because changing CCPhysicsSprite to CCSprite throws zero errors:
- (void)spawnBallAtPoint:(CGPoint)point
{
count++;
CCSprite *sprite = [CCSprite spriteWithFile:@"ball.png" rect:CGRectMake(0, 0, 52, 52)];
sprite.position = point;
[self addChild:sprite];
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
bodyDef.position.Set(point.x / PTM_RATIO, point.y / PTM_RATIO);
bodyDef.userData = sprite;
b2Body *body = world->CreateBody(&bodyDef);
b2CircleShape circleShape;
circleShape.m_radius = (26.0 / PTM_RATIO);
b2FixtureDef fixtureDef;
fixtureDef.shape = &circleShape;
fixtureDef.density = 1.0f;
fixtureDef.friction = 0.2f;
fixtureDef.restitution = 0.8f;
body->CreateFixture(&fixtureDef);
}
I've been looking around and can't find a real answer (as all the sample code uses CCPhysicsSprite in this way without error). I'm sure I'm making a stupid mistake but I guess that's to be expected when learning something new :P
Thanks in advanced!