xcode 在屏幕周围随机移动对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5034327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moving an object randomly around the screen
提问by thenameisnick
I'm trying to animate a UIButton to move randomly around the screen in different directions. The code below is kind of working. The button will begin moving along a random path, however, it then just continues to move back and forth between point A and point B.
我正在尝试为 UIButton 设置动画以在屏幕上沿不同方向随机移动。下面的代码有点工作。按钮将开始沿随机路径移动,但是,它会继续在 A 点和 B 点之间来回移动。
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
[UIView setAnimationRepeatCount:1000];
[UIView setAnimationRepeatAutoreverses:YES];
CGFloat x = (CGFloat) (arc4random() % (int) self.view.bounds.size.width);
CGFloat y = (CGFloat) (arc4random() % (int) self.view.bounds.size.height);
CGPoint squarePostion = CGPointMake(x, y);
button.center = squarePostion;
[UIView commitAnimations];
How can I get it to keep moving to a new random point every time it changes directions, instead of simply moving back and forth?
我怎样才能让它在每次改变方向时继续移动到一个新的随机点,而不是简单地来回移动?
Thanks!
谢谢!
回答by meronix
try this:
尝试这个:
-(void)animationLoop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1];
// remove:
// [UIView setAnimationRepeatCount:1000];
// [UIView setAnimationRepeatAutoreverses:YES];
CGFloat x = (CGFloat) (arc4random() % (int) self.view.bounds.size.width);
CGFloat y = (CGFloat) (arc4random() % (int) self.view.bounds.size.height);
CGPoint squarePostion = CGPointMake(x, y);
button.center = squarePostion;
// add:
[UIView setAnimationDelegate:self]; // as suggested by @Carl Veazey in a comment
[UIView setAnimationDidStopSelector:@selector(animationLoop:finished:context:)];
[UIView commitAnimations];
}
and just add a counter (int) inside the method to check if it's executed more than 1000 times, if wanna stop it...
只需在方法中添加一个计数器(int)来检查它是否执行了 1000 次以上,如果想停止它......