1

我有一个问题,在创建许多 box2d 实体并将它们添加到世界后,我的应用程序在迭代世界内部的实体时崩溃并出现 EXEC_BAD_ACCESS 错误,这是我创建实体的方式:

for(CXMLElement *node in obstaclesArr)
{
    b2BodyDef nObstacleBody;
    b2Body *obsBody;
    CCSprite *obstacle;

    obstacle = [CCSprite spriteWithFile:[NSString stringWithFormat:@"%@.png",[[node attributeForName:@"body"]stringValue]]];

    NSString *strX = [[node attributeForName:@"x"]stringValue];
    NSString *strY = [[node attributeForName:@"y"]stringValue];

    float x;
    float y;

    x = [strX floatValue];
    y = [strY floatValue];

    obstacle.tag = E;
    obstacle.position = ccp(x,y);
    [self addChild:obstacle z:9];

    nObstacleBody.type = b2_staticBody;
    nObstacleBody.position.Set(x/PTM_RATIO, y/PTM_RATIO);
    nObstacleBody.userData = obstacle;
    obsBody = world->CreateBody(&nObstacleBody);

    [[GB2ShapeCache sharedShapeCache]addFixturesToBody:obsBody forShapeName:[[node attributeForName:@"body"]stringValue]];
    [obstacle setAnchorPoint:[[GB2ShapeCache sharedShapeCache]anchorPointForShape:[[node attributeForName:@"body"]stringValue]]];
}

这是发生崩溃的地方:

for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
{
    if (b->GetUserData() != NULL) {
        //Synchronize the AtlasSprites position and rotation with the corresponding body
        CCSprite *myActor = (CCSprite*)b->GetUserData();
        myActor.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);//<-- crashes in this line
        myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());
    }   
}

我不知道为什么会崩溃,有人可以帮我吗?

4

2 回答 2

1

可能是您的 myActor 不是 cocos2d 对象?

或者

您正在从图层中移除 (removeChild:) 并尝试在之后访问?在这种情况下,保留计数将减少,并且对象将不再存在..

于 2012-07-24T05:38:05.420 回答
1

您可以通过检查 b2Body 中的 Userdata 类型来避免崩溃。

for (b2Body* b = world->GetBodyList(); b; b = b->GetNext())
    {
        if (b->GetUserData() != NULL) {
            //Synchronize the AtlasSprites position and rotation with the corresponding body
            CCSprite *myActor = (CCSprite*)b->GetUserData();

            if(myActor && [myActor isKindOfClass:[CCSprite class]] )
            {
                myActor.position = CGPointMake( b->GetPosition().x * PTM_RATIO, b->GetPosition().y * PTM_RATIO);//<-- crashes in this line
                myActor.rotation = -1 * CC_RADIANS_TO_DEGREES(b->GetAngle());  
            }
        }   
    }
于 2012-07-24T05:45:30.267 回答