I have an NSMutable array that I want to add Sprites to so that I can check them if they’ve hit the wall. I use this code to do so:
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;
}
}
}
However, when I build and run, I get the console output of ‘(null)’ and ‘HELP.’ The method before the ‘updator’ is called from touchesEnded. Can someone see what I’m doing wrong?
Thank you!
Why do you want to add bullets to another array? You already have a batch node that contains them all which is
_layer.children.Are you sure that the array itself (
bulletsArray) is not nil? where is it initialized?Finally you should consider looping with CCARRAY_FOREACH which is more performant.