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 に答える