i'm making a game where random obstacles fall from the top of the screen and the player has to avoid them. i'm having trouble implementing a method to delete the nodes (obstacles) that fall below the screen. although it may seem simple the way I'm spawning the obstacles has made it confusing. here is how i spawn the obstacles:
- (void)spawnNewObstacles
{
//spawn obstacles
SKSpriteNode *obstacle = [SKSpriteNode spriteNodeWithImageNamed:@"black.png"];
int position = arc4random() % 320 + 1;
obstacle.position = CGPointMake(position, 800);
obstacle.size = CGSizeMake(200, 20);
obstacle.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:obstacle.frame.size];
obstacle.physicsBody.dynamic = YES;
[self addChild:obstacle];
[obstacles addObject:obstacle]; //obstacles is an NSMutableArray
[obstacle.physicsBody applyImpulse:CGVectorMake(0, -80.0f)];
[self performSelector:@selector(spawnNewObstacles) withObject:nil afterDelay:0.25];
}
and here is how i'm trying (but failing) to delete the ones that fall below the screen:
-(void)update:(CFTimeInterval)currentTime
{
for(int i=0;i<obstacles.count;i++)
{
NSLog(@"Removed an Obstacle"); //this log isn't showing so i concluded that it wasn't working
SKSpriteNode *obstacle = [obstacles objectAtIndex:i];
if(obstacle.position.y<0)
{
[obstacle removeFromParent];
}
}
}
how would u guys suggest i do this?
p.s. plz explain with code...
From the sound of it, I'm guessing you haven't initialized the obstacles
array with a line like this:
obstacles = [NSMutableArray array];
Set a breakpoint and check if the obstacles
variable is non-nil.
Other than that the code looks okay. Except you should prefer to use fast enumeration - it's safer (index out of bounds can not occur), faster and easier to read:
for (SKSpriteNode* obstacle in obstacles)
{
NSLog(@"Removed an Obstacle");
if (obstacle.position.y < 0)
{
[obstacle removeFromParent];
}
}