2013-10-25 2 views
1

두 개의 스프라이트가 동시에 터치되면 앱이 중단됩니다. 나는 스프라이트 중 하나를 만지면동시에 두 개의 스프라이트를 터치하면 충돌이 발생합니다. (cocos2d-iphone)

-(void)addEnemy 
{ 
    enemy = [CCSprite spriteWithFile:@"enemy.png"]; 
    enemy.position = ccp(winsize.width/2, winsize.height/2); 
    [spriteSheet addChild:enemy]; 
    [spritetiles addObject:enemy]; //spritetiles is NSMutableArray 
} 

터치 코드

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint location = [self convertTouchToNodeSpace: touch]; 
    for (CCSprite *target in [spriteSheet children]) { 
    if (CGRectContainsPoint(target.boundingBox, location)) { 
     [target stopAllActions]; 
     [spriteSheet removeChild:target cleanup:YES]; 
     [spritetiles removeObject:target]; 
    } 
    } 
} 

는, 에러가 없다,하지만 난 두 개의 스프라이트를 (언젠가 어떤 스프라이트 '위치 근처)를 터치하면 앱이 충돌합니다, 코드 라인에서 "if (CGRectContainsPoint (target.boundingBox, location)) {", 어떻게 해결할 수 있습니까? 감사

+0

원하는 경우 코드의 일부를 보여 해달라고 도움. ccTouchesBegan의 'location'은 어디에서 왔으며 addEnemy의 _bomb은 무엇입니까? – YvesLeBorg

+0

@ YvesLeBorg 죄송합니다. 지금 코드를 업데이트했습니다. 제발 한번보세요. – yegomo

+0

hmmm ... iterating하는 동안 배열 ([spriteSheet children])을 수정하는 것에주의하십시오. – YvesLeBorg

답변

2

당신이 루프의 일부 요소를 제거해야 할 때 배열을 반복하기 위해

사용 reverseEnumerator 업데이트 :

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{ 
    UITouch *touch = [touches anyObject]; 
    CGPoint location = [self convertTouchToNodeSpace: touch]; 

    for (CCSprite *target in [spriteSheet.children reverseObjectEnumerator]) { 
     if (CGRectContainsPoint(target.boundingBox, location)) { 
      [target stopAllActions]; 
      [spriteSheet removeChild:target cleanup:YES]; 
      [spritetiles removeObject:target]; 
     } 
    } 
} 
+0

매우 감사합니다. – yegomo

+0

@yegomo는 적절한 감사를 위해 upvote도 잊지 마십시오. – YvesLeBorg

+1

아니요 아니요, 실제로는 필요한 것은 reverseEnumerator를 사용하는 것입니다. 역순으로 열거 할 때 배열에서 현재 반복 된 객체를 제거하는 것은 합법적입니다. – LearnCocos2D