views:

169

answers:

1

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];
}
+2  A: 

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:

astroidArray = [[NSMutableArray alloc] init];

... should only happen once, not every time you create a new asteroid.

Daniel Earwicker
Also, it's leaking an array on every pass through the loop.
smorgan
what should I change in my code to fix this if I might ask ?
OMG thank you ! fixed it perfectly, sorry I'm very new to arrays so this kind of threw me off balance.
No problem, traditionally at this point you click the green check mark!
Daniel Earwicker