Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...