在屏幕上随机移动一个物体

7
我正在尝试使一个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个回答

8

试试这个:

    -(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次,如果想要停止它...


2
你可能还需要在其中添加[UIView setAnimationDelegate:self];。 - Carl Veazey
@Carl Veazey:你说得对,我忘了它了,我会在新的编辑中添加它,谢谢。 - meronix
如何使其连续移动? - Badal Shah
谢谢你的回答。这个方法非常有效。但是我有一个问题,如何对多个对象执行此操作? - Pradeep Reddy Kypa

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
    })
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接