在屏幕上随机移动对象

the*_*ick 6 iphone xcode objective-c ios

我正在尝试动画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];
Run Code Online (Sandbox Code Playgroud)

每次改变方向时,我怎样才能让它继续移动到一个新的随机点,而不是简单地来回移动?

谢谢!

mer*_*nix 7

试试这个:

    -(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];
    }
Run Code Online (Sandbox Code Playgroud)

并在方法中添加一个计数器(int)来检查它是否执行了1000次以上,如果想要停止它...

  • 您可能需要添加[UIView setAnimationDelegate:self]; 在那里. (2认同)