2012-07-17 93 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

相關問題