当同时触摸两个精灵时,应用程序会崩溃。
-(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 :(得分:2)
<强>更新强>
当您需要在for循环中删除元素时,使用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];
}
}
}