在iOS游戏中获取所有连接b2Body

时间:2011-12-04 09:10:23

标签: ios cocos2d-iphone box2d box2d-iphone

我正在开发一款带有cocos2d的iPhone游戏,适用于iPhone的box2d。我这里有一个问题。 enter image description here

从上面的截图中可以看出,这些球是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" method是一个递归方法,编写如下

- (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有任何想法或任何算法来执行此功能,我非常感谢

非常感谢您的支持。

1 个答案:

答案 0 :(得分:0)

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

球只是不停地检查周围,我没有标记"发现&要删除球"。

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