1

저는 현재 Player와 Ball (Monster 클래스의 아들)의 두 클래스를 사용합니다. D 패드를 사용하면 화면에서 플레이어를 움직일 수 있고 볼은 화면에서 계속 튀어 오릅니다. ViewController에서 나는 플레이어의 NSMutableArray와 볼의 NSMutableArray를가집니다.하위보기 간의 충돌을 감지하는 방법은 무엇입니까?

Player *m = [[Car alloc]init]; 
    [players addObject:m]; 
    [self.view addSubview:m.image]; 

    joypad = [[Joypad alloc] initWithPlayer:players[0]]; 
    [self.view addSubview: joypad.pad]; 
    [self.view addSubview:joypad.movingPad]; 


    monsters = [NSMutableArray arrayWithCapacity:MAX]; 
    for(int i = 0; i < MAX; ++i) 
    { 
     int radius = rand()%100; 
     int deltax = rand()%5 + 1; 
     int deltay = rand()%5 +1; 
     Monster *ball = [[Ball alloc] initWithRadius:radius andDX:deltax DY:deltay]; 
     [self.view addSubview:ball.image]; 
     [ball startMoving]; 
    } 

볼과 공이있는 볼과 플레이어 간의 충돌을 어떻게 감지 할 수 있습니까? enter link description here

은 내가 VievController의 viewDidLoad에이 방법 (checkCllisions)를 호출하여 시도했지만 어떤 메시지를 표시하지 않습니다

-(void) checkCollisions{ 
    [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(collisions) userInfo:nil repeats:YES]; 
} 

-(void) collisions{ 

    for(int i = 0; i < [players count]; i++){ 
     Player *p = players[i]; 
     CGRect f = CGRectMake(p.image.frame.origin.x, p.image.frame.origin.y, p.image.frame.size.width, p.image.frame.size.height); 
     for (int k = 0; k < [monsters count]; i++){ 
      Monster *m = monsters[i]; 
      CGRect fm = CGRectMake(m.image.frame.origin.x, m.image.frame.origin.y, m.image.frame.size.width, m.image.frame.size.height); 
      if(CGRectIntersectsRect(f, fm)) 
       NSLog(@"collision"); 
     } 
    } 
} 

답변

0

collision 방법의 내부 루프의 두 가지 오류가 있습니다를 : 당신이해야 i 대신 k을 증가시키고 monsters[i]monsters[k]이어야합니다. CGRects의 할당이 단순화 될 수

참고 :

-(void) collisions{ 
    for(int i = 0; i < [players count]; i++){ 
     Player *p = players[i]; 
     CGRect f = p.image.frame; 
     for (int k = 0; k < [monsters count]; k++){ 
      Monster *m = monsters[k]; 
      CGRect fm = m.image.frame; 
      if(CGRectIntersectsRect(f, fm)) 
       NSLog(@"collision"); 
     } 
    } 
} 
+0

여전히 감사 메시지 아무것도하지 않는 내가 내가 주목하지 않았다 ++ 대신 K의 ++. 어떤 아이디어? – Spale350z

+0

@ Spale350z : * 두 가지 문제를 해결 했습니까? - 미안, 나는 더 좋은 생각이 없어. CGRect를 NSLog()해야만 예상 한 내용이 포함되어 있는지 확인할 수 있습니다. –

+0

좋아,이 줄이 빠져 있다는 것을 알았습니다. [monsters addObject : m] 이제 마틴에게 감사드립니다. – Spale350z

관련 문제