2012-07-17 91 views
2

我有一个NSMutable数组,我想添加Sprites以便我可以检查它们是否已经撞到墙上。我用这个代码,可以这样做:nsmutablearray调用时不添加对象

NSString *bulletName = [NSString stringWithFormat:@"tank%d_bullet.png", _type]; 
bullet = [CCSprite spriteWithSpriteFrameName:bulletName]; 
bullet.tag = _type; 
bullet.position = ccpAdd(self.position, ccpMult(_shootVector, _turret.contentSize.height));   
CCMoveBy * move = [CCMoveBy actionWithDuration:duration position:actualVector]; 
CCCallBlockN * call = [CCCallBlockN actionWithBlock:^(CCNode *node) { 
    [node removeFromParentAndCleanup:YES]; 
}]; 

if (!bulletIsGone) { 
    [self schedule:@selector(updator:) interval:0.01]; 

} 
else { 
    [self unschedule:@selector(updator:)]; 
} 
[bullet runAction:[CCSequence actions:move, call, nil]]; 
[_layer.batchNode addChild:bullet]; 
[bulletsArray addObject:bullet]; 
if ([bulletsArray objectAtIndex:0] == nil) { 
    NSLog(@"HELP"); 
} 
NSLog(@"%@", [bulletsArray objectAtIndex:0]); 


} 

-(void)updator: (ccTime) dt{ 

for(CCSprite *bulletz in bulletsArray){ 
    NSLog(@"this is the for loop"); 
    CGRect rect1 = CGRectMake(bulletz.position.x - bulletz.contentSize.width/2, bulletz.position.y - bulletz.contentSize.height/2, 20, 20); 
    if ([_layer isWallAtRect:rect1]) { 
     NSLog(@"bulletHitWall"); 
     [_layer.batchNode removeChild:bulletz cleanup:NO]; 
     bulletIsGone = YES; 
    } 
} 

} 

然而,当我建立和运行,我得到的“(空)”和控制台输出“HELP”。 'updator'之前的方法是从touchesEnded中调用的。有人可以看到我做错了什么吗? 谢谢!

回答

1

为什么要添加项目符号到另一个数组?您已有一个批处理节点,其中包含全部为_layer.children的批处理节点。 ()不是零?它在哪里初始化?

最后,你应该考虑与更高性能的CCARRAY_FOREACH循环。

3

你初始化数组吗?这似乎像最可能的原因

在您的viewDidLoad方法尝试......

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    bulletsArray = [NSMutableArray alloc] init]; 
} 
2

由于NSMutableArray不能抱nil对象,只有这样的条件

[bulletsArray objectAtIndex:0] == nil 

计算结果可能truebulletsArraynil。您需要确保数组已正确分配。一个典型的地方是你的班级的指定初始值。

+0

** facepalm **谢谢:/ – Jeeter 2012-07-17 00:50:35

相关问题