0

我正在用 cocos2d、box2d 为 iPhone 开发一款 iPhone 游戏。我这里有一个问题。 在此处输入图像描述

从上面的截图可以看出,这些球是 b2Body。一切顺利,除了一件事。当我点击一个球时,我希望将其从屏幕上移除,并且效果很好。

但是,我也需要删除所有具有相同颜色的连接球。例如,当我点击底部的红球时,与这个被点击的球相交的每个红球也应该被移除。

此方法管理点击位置

- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    for( UITouch *touch in touches ) {
    CGPoint location = [touch locationInView: [touch view]];

    location = [[CCDirector sharedDirector] convertToGL: location];
    b2Vec2 locationWorld = b2Vec2(location.x/PTM_RATIO, location.y/PTM_RATIO);

    // go through every single b2Body
    for(b2Body *b = world->GetBodyList(); b; b=b->GetNext()) {    
        if (b->GetUserData() != NULL) {

            b2Fixture *bf = b->GetFixtureList();

            // check which ball is tapped
            if (bf->TestPoint(locationWorld)) {
                [self destroyBall:b];
            }
        }        
    }
}

“destroyBall”方法是递归方法,写法如下

- (void) destroyBall:(b2Body *)body_ {
CCSprite *bodySprite = (CCSprite *) body_->GetUserData();
CGFloat h2 = bodySprite.contentSize.height / 2;
CGFloat w2 = bodySprite.contentSize.width / 2;

b2Vec2 p1 = b2Vec2((bodySprite.position.x - w2) / PTM_RATIO, (bodySprite.position.y - h2) / PTM_RATIO);
b2Vec2 p2 = b2Vec2((bodySprite.position.x - w2) / PTM_RATIO, (bodySprite.position.y + h2) / PTM_RATIO);
b2Vec2 p3 = b2Vec2((bodySprite.position.x + w2) / PTM_RATIO, (bodySprite.position.y + h2) / PTM_RATIO);
b2Vec2 p4 = b2Vec2((bodySprite.position.x + w2) / PTM_RATIO, (bodySprite.position.y - h2) / PTM_RATIO);

// go through all b2Body to check which one is intersect with body_
for (b2Body *b = world->GetBodyList(); b; b = b->GetNext()) {
    if ((b->GetUserData() != NULL) && (b != body_)) {
        CCSprite *newBall = (CCSprite *)b->GetUserData();

        b2Fixture *bf = b->GetFixtureList();
        if (bf->TestPoint(p1) || bf->TestPoint(p2) || bf->TestPoint(p3) || bf->TestPoint(p4)) {
            if (bodySprite.tag == newBall.tag) {
                [self destroyBall:b];
            }
        }
    }
}

CCSpriteBatchNode *batch = (CCSpriteBatchNode *) [self getChildByTag:kTagBatchNode];
[batch removeChild:bodySprite cleanup:YES];

world->DestroyBody(body_);
}

这个想法很简单,当A球被轻敲时,它会寻找周围正在击球A球的其他球。如果是B球,则该过程将再次与B球一起进行,直到没有击球球为止。

但是,递归函数似乎不停地运行:(

如果您有任何想法或任何算法来使用 box2d 执行此功能,我将不胜感激

非常感谢您的支持。

4

1 回答 1

0

我自己找到了解决方案。我在递归方法中犯了一个大而可怕的错误,我没有做一个停止点,所以该方法永远运行。

球只是不停地检查,我没有标记“找到并要删除球”。

我通过创建一个 NSMutableArray 来修复它,并在找到接触球时将 CCSprite 添加到此 NSMutableArray 中。递归方法只调用在 NSMutableArray 中找不到的球

于 2011-12-05T03:20:08.220 回答