我最近才开始搞乱 cocos2d 的 Box2D 集成,虽然大部分过程都很简单直接,但在使用 CCPhysicsSprite(将 b2body 与 sprite 集成的 CCSprite 子类)时,我一直遇到 EXC_BAD_ACCESS 错误。我正在使用的代码是:
- (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;
}
此代码触发 EXC_BAD_ACCESS,我知道它是 CCPhysicsSprite,因为将 CCPhysicsSprite 更改为 CCSprite 会引发零错误:
- (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);
}
我一直在环顾四周,找不到真正的答案(因为所有示例代码都以这种方式使用 CCPhysicsSprite 没有错误)。我确定我犯了一个愚蠢的错误,但我想在学习新东西时这是可以预料的:P
先谢谢了!