xcode iphone ball animation
What I want to do is that every 开发者_开发技巧ten second a ball is created outside of the screen, and when it is created it move to the center of the screen. How can I do this?
In your view controller set up a UIImageView property for your ball, contruct the ball and make sure its starting location is off the viewable area of the creen and then use an NSTimer which fires every ten seconds which callas a method that animates your ball across the screen to the centre.
-(void)viewDidLoad{
NSTimer *ballTimer = [NSTimer timerWithTimeInterval:10.0
target:self
selector:@selector(moveBall)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:ballTimer forMode:NSRunLoopCommonModes];
myBall = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"MyBallImageFile.png"]];
myBall.center = CGPointMake(320/2, [self randNumBetween:-50:-100]);
[self.view addSubview:myBall];
}
-(void)moveBall{
myBall.center = CGPointMake(320/2, [self randNumBetween:-50:-100]);
[UIView animateWithDuration:5.0 animations:^{
myBall.center = CGPointMake(320/2, 480/2);
}];
}
----------EDIT------------
- (CGFloat)randNumBetween:(CGFloat) min :(CGFloat) max{
CGFloat difference = max - min;
return (((CGFloat) rand()/(CGFloat)RAND_MAX) * difference) + min;
}
- (void)viewDidLoad {
[super viewDidLoad];
myBallImage = [[UIImage imageNamed:@"ball.png"] retain];
myTimer = [NSTimer scheduledTimerWithTimeInterval:10.0 target:self selector:@selector(addBallToScreen) userInfo:nil repeats:YES];
}
- (void)viewDidUnload {
[myBallImage release];
[myTimer invalidate];
}
- (void)addBallToScreen {
//Create the imageView
UIImageView *imageView = [[UIImageView alloc] initWithImage:myBallImage];
imageView.transform = CGAffineTransformMakeTranslation(1000, 1000);
[self.view addSubview:imageView];
[imageView release];
//Animate the image view
[UIView beginAnimations:nil context:nil];
imageView.transform = CGAffineTransformMakeTranslation(50, 50);
[UIView commitAnimations];
}
精彩评论