Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

DifferentialApp

macrumors regular
Original poster
May 14, 2010
108
0
Hi!

I am trying to build an app that has a whole bunch of images floating around and when it hits your ship, it displays a message and maybe an animation.

Right now, i can only get it to make one ball move around. How do I make more than one? I am using an NSTimer. Is this the best way to do it?

If you need the code I am using, just let me know.

Thanks!
 
You want to create an array of UIImageViews - probably a NSMutableArray so you can add and remove items. Something like this:

Code:
// /in the .h file
NSMutableArray *meteorArray;

//in the .m file
-(void)createMeteors{

    if (meteorArray==nil){
    meteorArray = [[NSMutableArray alloc] init];
    }

    UIImage *meteorImage = [UIImage imageNamed:@"meteor.png"];
    UIImageView *newView;

    for (int i = 0; i< 10; i++){  //creates 10 meteors
        newView= [[UIImageView alloc] initWithImage: meteorImage];

        //pick a position on the screen
        int x = arc4random()%320; 
        int y = arc4random()%480; //negative y = off the top
        newView.center = CGPointMake (x,y);

        [self.view addSubview: newView]; //adds meteors as subviews
        [meteorArray addObject: newView]; //add to array
        [newView release];
    }

}

Then you can have your timer call "moveMeteors" to move the rocks, check collisions, etc.

Code:
-(void)moveMeteors{
	for (UIImageView* myRock in meteorArray ){
		//move new center down
		CGPoint newCenter = myRock.center;
		newCenter.y = newCenter.y +1;
		
		if (newCenter.y > 480){ // if off the bottom
			newCenter.y=0;   //pop to top
			newCenter.x = arc4random()%320;  //and pick new x position
		}
		
		myRock.center = newCenter;
}
	}
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.