保存被破坏的接触体

时间:2013-05-14 07:34:21

标签: cocos2d-iphone box2d box2d-iphone

在我的代码中,我想销毁两个联系机构中的一个。在beginContact中,调用CCPhysicsSprite中的以下方法:

-(void)contactMade:(CCPhysicsSprite*)contactedSprite {
int spriteTag1 = self.tag;
int spriteTag2 = contactedSprite.tag;

if (((spriteTag1 == 3) && (spriteTag2 == 4)) || ((spriteTag1 == 4) && (spriteTag2 == 3)) {

   CCPhysicsSprite* heroSprite = (CCPhysicsSprite*)[self getChildByTag:4];
    b2World* world;

    world->DestroyBody(heroSprite.b2Body);
    heroSprite.b2Body = NULL;
    [heroSprite.parent removeChild:heroSprite];
}

我收到SIGABRT指向

的信号
b2Assert(m_bodyCount > 0);

搜索此问题后。我读到在时间步之后必须保存并销毁接触体。考虑到我已经在CCPhyscisSprite中设置了我的联系条件,我怎么能这样做呢。

1 个答案:

答案 0 :(得分:1)

您可以向物理对象添加标志(例如:isDead ...),在碰撞事件中只需将该标志值更改为TRUE。

-(void) CollisionBegin:(b2Fixture*)target With:(b2Fixture*) source
{    
    if ( target->GetBody()->GetType() == b2_dynamicBody)
    {
        yourCustomClass *temp = (yourCustomClass *)target->GetBody()->GetUserData();
        temp->isDead = true ;
    }
}

然后在步骤之后的更新函数中获取所有物理世界的对象并通过flag(Here:isDead)找到该特定对象,并销毁它。

-(void) update: (ccTime) dt
{

    int32 velocityIterations = 8;
    int32 positionIterations = 3;

    world->Step(dt, velocityIterations, positionIterations);

    // remove your box2d object here , after step function

    for ( b2Body *b = world->GetBodyList(); b; )
    {
        b2Body *baba = b->GetNext();
        if ( b->GetUserData() != NULL && b->GetType() == b2_dynamicBody)
        {
            yourCustomClass *t = (yourCustomClass *)b->GetUserData();
            if ( t->isDead )
            {
                world->DestroyBody(b);    // remove physical body
                [self removeChild:t];     // remove node from super layer
            }
        }
        b = baba ;
    }
}
相关问题