2

我正在将 2d 游戏从 UIKit 移植到 Cocos2d。其中一部分为五个不同的方块设置框架,当我使用 UIKit 时看起来像这样:

- (void)setFrames {
    [playerSquare setCenter:CGPointMake(160, 240)];

    for(int iii = 0; iii < [squares count]; iii++) {
        int randX = arc4random() % 321;
        int randY = arc4random() % 481;

        [(UIButton*)[squares objectAtIndex:iii] setFrame:CGRectMake(randX, randY, [(UIButton*)[squares objectAtIndex:iii] frame].size.width, [(UIButton*)[squares objectAtIndex:iii] frame].size.height)];

        CGRect playerRect = CGRectMake(80, 160, 160, 160);

        for(UIButton* b in squares) {
            if((CGRectIntersectsRect(b.frame, [(UIButton*)[squares objectAtIndex:iii] frame]) && ![b isEqual:[squares objectAtIndex:iii]])) {
                //make sure no two squares touch
                iii--;
                break;
            } else if(CGRectIntersectsRect(playerRect, [(UIButton*)[squares objectAtIndex:iii] frame])) {
                //no square is close to center of the screen
                iii--;
                break;
            } else if(!CGRectContainsRect(CGRectMake(10, 10, 300, 460), [(UIButton*)[squares objectAtIndex:iii] frame])) {
                //no square is close to the edges of the screen
                iii--;
                break;
            }
        }
    }
}

到目前为止,我已经尝试在 cocos2d 中完成同样的事情:

- (void)setFrames {
    for(int idx = 0; idx < [squares count]; idx--) {
        int randX = arc4random() % 321;
        int randY = arc4random() % 481;

        [(CCSprite*)[squares objectAtIndex:idx] setPosition:ccp(randX, randY)];

        CGRect playerRect = CGRectMake(80, 160, 160, 160);

        for(CCSprite* b in squares) {
            if( (CGRectIntersectsRect(b.boundingBox, [(CCSprite*)[squares objectAtIndex:idx] boundingBox]) && ![b isEqual:[squares objectAtIndex:idx]]) ) {
                //make sure no two squares touch
                idx--;
                break;
            } else if(CGRectIntersectsRect(playerRect, [(CCSprite*)[squares objectAtIndex:idx] boundingBox])) {
                //no square is close to center of the screen
                idx--;
                break;
            } else if(!CGRectContainsRect(CGRectMake(10, 10, 300, 460), [(CCSprite*)[squares objectAtIndex:idx] boundingBox])) {
                //no square is close to the edges of the screen
                idx--;
                break;
            }
        }
    }
}

但是这种修改后的方法不起作用。其中一个方块被放置在正确的位置,但其他四个总是在 cocos2d 点 0、0 处生成。(屏幕的左下角)谁能指出我正确的方向?

4

1 回答 1

1

我刚刚发现了问题-不敢相信我做到了。在此方法的某一时刻,我将 for 循环设置为:

for(int idx = [squares count] - 1; idx >= 0; idx--)

代替

for(int idx = 0; idx < [squares count]; idx++)

正如您在上面的代码中看到的那样,我忘记将循环的递减部分更改为从递减递增。所以,只有第一个精灵被设置的原因是循环从 0 开始,然后idx递减,直到它超过 int 的下限并到达ints 的上限,大于[squares count]. 所以,我的新代码的唯一问题是 idx++ 和 idx-- 之间的区别。

令人沮丧的错误。

于 2011-12-29T21:22:08.963 回答