2011-12-29 2 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; 
      } 
     } 
    } 
} 

그러나이 수정 된 방법은 작동하지 않습니다. 사각형 중 하나가 적절한 위치에 놓이게되지만 나머지 4 개는 항상 0, 0의 cocos2d 지점에서 생성됩니다 (화면의 왼쪽 하단). 누군가 올바른 방향으로 나를 가리킬 수 있습니까?

+0

randX randY 좌표 란 무엇입니까? 나는 4 개의 스프라이트 중 3 개의 스프레드가 0,0이 될 것 같지 않으므로 다른 위치를 다시 변경한다고 상상할 수 있습니다. – LearnCocos2D

+0

for 루프 선언을 한 번 더보세요 :) 모든 것이 명확 해집니다. –

답변

1

나는 문제를 알아 냈습니다. 나는 이것을 한 것으로 믿을 수 없습니다. 이 방법의 한 시점에서, 나는이 루프로 설정했다 :

대신

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

당신은 내가 이상이 코드에서 볼 수 있듯이

, 나는 감소 부분을 변경하는 것을 잊었다 감소에서 증가하는 루프의 수입니다. 따라서 첫 번째 스프라이트 만 설정된 이유는 루프가 0에서 시작했기 때문에 idx이 int의 하한을 초과하여 int s의 상한에 도달 할 때까지 감소하여 [squares count] 이상이었습니다. 그래서 새로운 코드의 유일한 문제점은 idx ++와 idx의 차이입니다.

실망스런 실수.