Question

In my iphone application I have several images. lets say some small square images. what I want is I want that small objects appear from the top of the screen at rondom times and leaves the screen from the bottom. I mean, for example, object randomly appeared from the x:30 y:0 point (x value must be random) and leaves from the x:30 y:460 with an animation.

I am programming an 2d racing game and they are the cars. hope it is clear.

edit: well I tried to change the frame the numbers belong to something else. But I could not have the frame of the image and also I could not figure out how to generate position randomly more than one time. since I was planning to put it on the viewDidLoad.

[UIView beginAnimations:@"myAnimation" context:nil];
CGRect Frame = image.frame;
if(Frame.origin.y == 340){
    Frame.origin.y = 260;
}else{
    Frame.origin.y = 340;
}
image.frame = Frame;
[UIView commitAnimations];
Was it helpful?

Solution

Your example code doesn't show what you are asking for. It's also really hard to guess what you want.

Here's my literal interpretation of what you have asked for

for (int i = 0; i < 100; i++) {

    CGRect startFrame = CGRectMake(arc4random_uniform(320), -50, 50, 50);
    CGRect endFrame   = CGRectMake(arc4random_uniform(320),  
                                   CGRectGetHeight(self.view.bounds) + 50, 
                                   50, 
                                   50);

    UIView *animatedView = [[UIView alloc] initWithFrame:startFrame];
    animatedView.backgroundColor = [UIColor redColor];

    [self.view addSubview:animatedView];

    [UIView animateWithDuration:2.f
                          delay:i * 0.5f
                        options:UIViewAnimationCurveLinear
                     animations:^{
                         animatedView.frame = endFrame;
                     } completion:^(BOOL finished) {
                         [animatedView removeFromSuperview];
                     }];
}

If you stick this in viewDidAppear: then you'll see 100 objects animate in the way you want. Obviously this is extremely inefficient and you may want to look at recycling the views etc but this shows how to animate views with UIView animation with some random points

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top