2011-12-29 99 views
2

我正在从UIKit移植到Cocos2d的2D游戏。它的一个部分,它设置了五个不同的正方形框架,看起来像这样,当我用的UIKit:Cocos2d CGRect逻辑

- (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处产生(屏幕的左下角)任何人都可以指向正确的方向吗?

+0

什么是randX randY坐标?我想他们对于4个精灵中的3个几乎不会是0,0,所以我只能想象你在其他地方再次改变位置。 – LearnCocos2D 2011-12-29 20:45:37

+0

再次查看for循环声明:)它将全部变得清晰。 – 2011-12-29 21:22:48

回答

1

我刚才发现了这个问题 - 不敢相信我这么做过。在这种方法的一个点,我有for循环设置为:

,而不是

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

正如你在我上面的代码中看到的,我忘了改减量部分的循环从递减增量。所以,只有第一个精灵被设置的原因是循环从0开始,然后idx递减,直到它覆盖int的下界并且去到int的上界,其大于[squares count]。所以,我的新代码唯一的问题是idx ++和idx--之间的区别。

令人沮丧的错误。