Random Image Movement

Discussion in 'iOS Programming' started by DifferentialApp, Jun 10, 2010.

  1. DifferentialApp macrumors regular

    May 14, 2010

    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.

  2. xsmasher macrumors regular


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

    // /in the .h file
    NSMutableArray *meteorArray;
    //in the .m file
        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.

    	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;

Share This Page