在屏幕上随机移动对象 [英] Moving an object randomly around the screen

查看:168
本文介绍了在屏幕上随机移动对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试动画UIButton以在不同方向上随机移动屏幕。下面的代码很有用。该按钮将开始沿着随机路径移动,然而,它继续在A点和B点之间来回移动。

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?

谢谢!

推荐答案

试试这个:

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

and just add a counter (int) inside the method to check if it's executed more than 1000 times, if wanna stop it...

这篇关于在屏幕上随机移动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆