0

我正在使用基于 box2d 的游戏,它检测到我的玩家身体与敌人身体碰撞,但是当我在碰撞点为敌人编写 destroybody 方法时,我的敌人无法摧毁并给出错误并且我的应用程序崩溃了。我给你看我的代码

std::vector<b2Body *>toDestroy; 
    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) 
        {
            CCSprite *spriteA = (CCSprite *) bodyA->GetUserData();
            CCSprite *spriteB = (CCSprite *) bodyB->GetUserData();
            if (spriteA.tag == 1 && spriteB.tag == 2) 
            {
                // SpriteA = PlayerSprite
                // SpriteB = EnemySprite
                NSString *t=[NSString stringWithFormat:@"Game Over"];
                label.string=t;
                [self removeChild:spriteB cleanup:YES];
                 world->DestroyBody(bodyB);
            } 
            else if (spriteA.tag == 2 && spriteB.tag == 1) 
            {
                //toDestroy.push_back(bodyB);
                NSLog(@"Enemy Touch");
            }
        }
    }

这里我的 spriteB 不能破坏。另一件事是敌人精灵在 Enemy.mm 文件中。

请帮我解决这个问题。提前致谢

4

1 回答 1

0

您在处理与玩家的敌人接触与玩家与敌人的接触不同(这只是事情的顺序)方面犯了一个根本错误,您应该将这两种情况视为相同,因为您无法知道它们到达的顺序。你也没有正确使用 toDestroy 。

std::vector<b2Body *>toDestroy; 
    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) 
        {
            CCSprite *spriteA = (CCSprite *) bodyA->GetUserData();
            CCSprite *spriteB = (CCSprite *) bodyB->GetUserData();
            if ((spriteA.tag == 1 && spriteB.tag == 2) ||(spriteA.tag == 2 && spriteB.tag == 1)) 
            {
                // SpriteA = PlayerSprite
                // SpriteB = EnemySprite
                NSString *t=[NSString stringWithFormat:@"Game Over"];
                label.string=t;
                [self removeChild:spriteB cleanup:YES];
                 toDestroy.push_back(bodyB);
            } 

        }
        }
//iterate and delete everything from toDestroy
于 2012-08-09T17:46:40.327 回答