开发者

Moving an object randomly around the screen

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.

[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!


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...


Swift 5 example of making one animation

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜