当我试图进行碰撞检测时收到EXC_BAD_ACCESS信号

时间:2013-05-06 07:28:24

标签: cocos2d-iphone

我坚持这个位置,不知道这出了什么问题,

我在项目中启用了ARC。我将softBody设为如下

Ball.h

    B2Body *body[NUM_SEGMENT];
    CCSprite *ball;

Ball.mm

    ball = [CCSprite spriteWithFile:@"Ball1.2.png"];
    ball.tag = 1;


    for(int i=0;i<NUM_SEGMENT;i++){
        float theta = deltaAngle*i;
        float x = radius * cosf(theta);
        float y = radius * sinf(theta);
        b2Vec2 circlePosition = b2Vec2(x/PTM_RATIO,y/PTM_RATIO);
        b2BodyDef bodyDef;
        bodyDef.type = b2_dynamicBody;
        bodyDef.position = (center + circlePosition);
        bodyDef.userData = &ball;
        body[i] = world->CreateBody(&bodyDef);
        outerBodyFixture[i]=body[i]->CreateFixture(&fixtureDef);
        [bodies addObject:[NSValue valueWithPointer:body[i]]];
    }

我已经按照以下方式给了瓷砖物理,

Tile.h

CCSprite *tile;

Tile.mm

tile = [layer1 tileAt:ccp(i, j)];
tile.tag = 0;
b2BodyDef tileDef;
tileDef.type = b2_staticBody;
tileDef.position.Set((tile.position.x+(tile.contentSize.width/2))/(PTM_RATIO), (tile.position.y + (tile.contentSize.height/2))/PTM_RATIO);
tileDef.userData = &tile;
tileBody = world->CreateBody(&tileDef);

现在我试图捕捉碰撞检测,我已经制作了代码,用于打印碰撞体的标签号。代码如下,

std::vector<MyContact>::iterator pos;
    for (pos=_contactListener->_contacts.begin();
         pos != _contactListener->_contacts.end(); ++pos) {
        MyContact contact = *pos;

        b2Body *bodyA = contact.fixtureA->GetBody();
        b2Body *bodyB = contact.fixtureB->GetBody();
        if (bodyA->GetUserData() != NULL && bodyB->GetUserData() != NULL) {

此时获取错误:EXC_BAD_ACCESS

        CCSprite *spriteA = (__bridge CCSprite *) bodyA->GetUserData();

此时获取错误:EXC_BAD_ACCESS

        CCSprite *spriteB = (__bridge CCSprite *) bodyB->GetUserData();


            printf("contact :%d \n",spriteB.tag);
        }
    }

不知道这段代码有什么问题,给我一些解决方法

1 个答案:

答案 0 :(得分:0)

您的问题是您在userData存储指向指针而不是指针本身的指针。

tile已指向CCSprite个实例,&tile指向指向CCSprite实例的指针,导致您的广告投放错误。

所以改成它:

tileDef.userData = tile;