I have an array an a timer that adds a new object to my array every 5 seconds but am running into a slight issue. I have a code that is called repeatably which moves the objects in my array but for some reason the previous object that spawns will stop moving when a new object is spawned into my array. How do I make it so every single object in the array is called, instead of just the one that spawns last?
Here’s my code that’s called to move the objects:
for (UIView *astroids in astroidArray) {
int newX = astroids.center.x + 0;
int newY = astroids.center.y + 1;
astroids.center = CGPointMake(newX,newY);
}
Edit: Sorry, here’s my code for my array:
// spawn the astroids every few seconds randomly along the x axis
// and remove them once they get off the screen
if ((gameStarted == YES) && (gameOver == NO)) {
int randomX = arc4random() % 320;
astroidArray = [[NSMutableArray alloc] init];
UIImage *astroid = [UIImage imageNamed:@"astroidwhite.png"];
UIImageView *astroids = [[UIImageView alloc] initWithImage:astroid];
//set X and Y of the new imageView
astroids.center = CGPointMake(randomX , -10);
//add to array
[astroidArray addObject:astroids];
//add to the view, so it gets displayed.
[self.view addSubview: astroids];
[astroids release];
}
It looks like you’re allocating a new array every time you allocate a new asteroid. You then add the new asteroid to the array, so it is the only one on the array.
Consequently, when you loop through the array, there’s only one asteroid on it.
Update:
So, to fix this, allocate the array once (during startup of your game?). Don’t create a new array every time.
This part:
… should only happen once, not every time you create a new asteroid.