2011-12-29 57 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--之間的區別。

令人沮喪的錯誤。