1

我最近才开始搞乱 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

先谢谢了!

4

1 回答 1

2

CCPhysicsSprite设置精灵的位置之前,您必须设置身体。我假设这条线是发生崩溃的地方:

sprite.position = point;

如果您查看CCPhysicsSprite它会覆盖 position/setPosition 以始终使用包含b2body对象的值。所以它真的访问了它的 b2body 属性,也就是nil那个时候 → Crash。通常,在创建 CCPhysicsSprite 后,您希望尽快设置其 .b2body - 可能会出现更多类似问题的情况,因为您需要先设置 .b2body 属性。

所以,移到sprite.position = point;下面sprite.b2Body = body;

于 2013-03-12T07:21:26.267 回答