在屏幕上随机移动对象

时间:2011-02-17 20:36:58

标签: iphone objective-c xcode 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];

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

谢谢!

2 个答案:

答案 0 :(得分: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];
    }

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

答案 1 :(得分:1)

Swift 5 制作一个动画的例子

@objc func didBecomeActive() {
    DispatchQueue.main.async {
        self.startAnimationCalm()
    }
}
    
func startAnimation() {
        
    let animatedShadow = UIView(frame: CGRect(origin: CGPoint(x: 10, y: 10), size: CGSize(width: 20, height: 20)))
    animatedShadow.clipsToBounds = true
    animatedShadow.layer.cornerRadius = 20/2
    animatedShadow.backgroundColor = UIColor.green
    animatedShadow.layer.borderWidth = 0
    self.view.addSubview(animatedShadow)
    
    UIView.animate(withDuration: 5, delay: TimeInterval(0), options: [.repeat, .curveEaseIn], animations: { () -> Void in
        
        let randomX = CGFloat.random(in: 14 ... 200)
        let randomY = CGFloat.random(in: 20 ... 600)
        
        animatedShadow.center = CGPoint(x: animatedShadow.frame.origin.x + randomX, y: animatedShadow.frame.origin.y + randomY)
        self.view.layoutIfNeeded()
    }, completion: { finished in
    })
}