无法在cocos2d-iphone中从self中删除目标

时间:2014-06-12 00:54:02

标签: cocos2d-iphone nsmutablearray

我使用以下代码创建一些精灵

-(void)dologic
{

 for (int i = 0; i < 3; i ++) {
    CCSprite *target = [CCSprite spriteWithFile:@"pig.png"];
    int x = arc4random() % 320;
    int y = arc4random() % 300;
    target.position = ccp(x, y);
    [self addChild:target];
    [_targets addObject:target];//_targets is nsmutablearray
 }
}


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

当触摸任何精灵时,所有精灵将首先从自我中删除,然后再次调用dologic创建三个新精灵,但我的代码只能删除我触摸的目标,我该如何删除所有精灵当我触摸屏幕时精灵?

2 个答案:

答案 0 :(得分:0)

首先,你在迭代它时修改数组,这不是一个好习惯。

如果您想在触摸任何目标时删除所有目标,可以尝试:

- (void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    CGPoint location = [self convertTouchToNodeSpace: touch];
    BOOL touchedASprite = NO;
    for (int i = 0; i < [_targets count] && !touchedASprite; ++i) {
        if (CGRectContainsPoint((CCSprite*)[_targets objectAtIndex:i].boundingBox, location)) {
            touchedASprite = YES;
        }
    }
    if (touchedASprite) {
        for (CCSprite *target in _targets) {
            [self removeChild:target cleanup:YES];
        }
        [_targets removeAllObjects];
        [self doLogic];
    }
}

答案 1 :(得分:0)

当你想在浏览数组中的所有对象时删除数组中的对象时,你应该这样做:

for (int i = (int)_targets.count - 1 ; i >= 0 ; i--) {
    CCSprite *target = _targets[i];
    if (CGRectContainsPoint(target.boundingBox, location)) {
        [_targets removeAllObjects];
        [self removeChild:target cleanup:YES];
        [self dologic];
    }
}

小心[NSArray count]返回无符号数,当[NSArray count]返回 0 时,([NSArray count]-1 NOT -1,应该将其强制转换为int