在屏幕右侧设置UIImageView

时间:2015-08-21 21:16:55

标签: ios objective-c uiimageview

我有一个名为ufo的UIImageView。它向左移动到屏幕外,直到你再也看不到了,我希望它在屏幕右侧重新生成并移入。左侧正在工作,但右侧不是。

if (ufo.center.x < (-ufo.frame.size.width/2)) {
            ufo.center = CGPointMake((backGround.frame.size.width -    (ufo.frame.size.width / 2)), ufo.center.y);
        }

它完全在右侧重生,而不是从屏幕上掉下来。我知道CGPointMake中应该有一个+,但是它在左侧是错误的!

有人可以帮忙吗?

谢谢。

2 个答案:

答案 0 :(得分:1)

根据您的标准,我会做以下的事情:

if (ufo.center.x < (backGround.frame.origin.x - (ufo.bounds.size.width / 2.0))) 
{
    //just guessing, since you haven't shown your animation code, but, add the following line:
    [ufo.layer removeAllAnimations];
    //you haven't shown enough, so here is another shot in the dark:
    [timer invalidate];
    ufo.center = CGPointMake((backGround.frame.size.width + (ufo.bounds.size.width / 2.0)), ufo.center.y);
}

以下 用于模仿游戏的行为,基于一些猜测(因为您还没有充分显示)以及您目前所拥有的信息提供。

根据您的标准,您的不明飞行物现在从右到左飞回我的屏幕并返回右侧:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self createMyUFOandMyBackground];
}

- (void)createMyUFOandMyBackground
{
    myBackground = [[UIImageView alloc] initWithFrame:self.view.bounds];
    myBackground.image = [UIImage imageNamed:@"background"];
    [self.view addSubview:myBackground];

    myUFO = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"ufo"]];
    myUFO.center = (CGPoint){myBackground.bounds.size.width + (myUFO.bounds.size.width / 2.0f), myBackground.center.y};
    [self.view addSubview:myUFO];

    [self createTimer];
}

- (void)createTimer
{
    myTimer = [NSTimer scheduledTimerWithTimeInterval:0.05f target:self selector:@selector(moveUFOToLeft) userInfo:nil repeats:YES];
}

- (void)moveUFOToLeft
{
    temp = 0;
    if (myUFO.center.x < (myBackground.frame.origin.x - (myUFO.bounds.size.width / 2.0)))
    {
        [myTimer invalidate];
        myTimer = nil;
        myUFO.center = CGPointMake((myBackground.frame.size.width + (myUFO.bounds.size.width / 2.0)), myUFO.center.y);
        [self restartMyTimerAfterSeconds];
    }
    else
    {
        temp = - arc4random_uniform(10);
        myUFO.center = CGPointMake(myUFO.center.x + temp, myUFO.center.y);
    }
}

- (void)restartMyTimerAfterSeconds
{
    //This is specific to your game; I will leave that to you.

    [self createTimer];
}

答案 1 :(得分:0)

我假设您在ufo之上添加了backGround,并尝试在计时器的帮助下将ufo从右侧移动到左上方。

在计时器方法

中使用以下源代码
//Constant which will allow ufo to be moved from right to left    
CGFloat temp = -2;
//Create new point after adding moving offset for ufo
CGPoint point = CGPointMake(ufo.center.x + temp, ufo.center.y);
//Check weather new points is moved away from background if so then assign new center to the right
if ((point.x + CGRectGetWidth(ufo.bounds)/2) < 0.0f) {
            point.x = CGRectGetWidth(ufo.bounds)/2 + CGRectGetMaxX(backGround.bounds)
        }
//Assign the new center to ufo for providing movement from its last position.
ufo.center = point;