I have a game that I wrote. I am about ready to call it finished but I found a bug. Basically the game gets slower as the longer you play. My guess is this is due to sprites that are still being drawn off screen. I will paste the code below but basically the sprite is created in the “addNewBall” method. In this method it is added to an array which calculates its motion. After the ball reaches a position where it is off the screen it is removed from the array which causes it to stop moving but it is still being “drawn” off screen. How do I remove the sprite so the processor no longer calculates it. Thanks in advance for your help!
Tanner
Code:
-(void) addNewBall {
NumberOfBalls = NumberOfBalls + 1;
int RandomXPosition = (arc4random() % 240) + 40;
NSString *BallFileString = @"OrangeBall.png";
switch (arc4random() % 5) {
case 1:
BallFileString = @"OrangeBall.png";
break;
case 2:
BallFileString = @"GreenBall.png";
break;
case 3:
BallFileString = @"YellowBall.png";
break;
case 4:
BallFileString = @"PinkBall.png";
break;
case 0:
BallFileString = @"BlueBall.png";
break;
}
Ball = [CCSprite spriteWithFile:BallFileString];
Ball.position = ccp(RandomXPosition, 520);
BallIsMoving = YES;
[self addChild:Ball z:10];
[AllObjectsArray_ addObject:Ball];
[BallArray_ addObject:Ball];
}
//And here is where it is removed...
if (Ball.position.y <= -100) {
[BallArray_ removeObject: Ball];
}
You seem to be missing some conditions in your removal method. Don’t you also want to remove the ball if its y position is greater than the screen height, or if its x position is off-screen? At any rate, in the same place that you’re removing the ball from the array, you should add:
I should also point out that your
BallArrayis probably redundant, since you’re adding all the balls to another node anyway. If the only children of that node areBalls, you can get the array of balls using itschildrenproperty. In this case, the child array would be:self.children(See http://www.cocos2d-iphone.org/api-ref/latest-stable/interface_c_c_node.html#a5e739ecda0c314283a89ac389dfca2fa for more info.)If you have non-Ball children on the same node, you might want to add an intermediate node to simplify the design so that you can use one less array.