首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在for循环中创建Box2d主体

在for循环中创建Box2d主体
EN

Stack Overflow用户
提问于 2012-07-23 14:03:34
回答 2查看 443关注 0票数 1

我有一个问题,在创建了许多box2d bodies并将它们添加到世界中后,我的应用程序在迭代世界中的bodies时出现EXEC_BAD_ACCESS错误而崩溃,下面是我如何创建bodies的方法:

代码语言:javascript
复制
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]]];
}

下面是崩溃发生的地方:

代码语言:javascript
复制
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());
    }   
}

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-24 13:45:30

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

代码语言:javascript
复制
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());  
            }
        }   
    }
票数 1
EN

Stack Overflow用户

发布于 2012-07-24 13:38:05

可能您的myActor不是cocos2d对象?

您正在从层(removeChild:)中删除,然后尝试访问吗?在这种情况下,保留计数将减少,对象将不再存在。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11607199

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档