2015-08-21 60 views
1

我有一个名为ufo的UIImageView。它正在屏幕外面移动,直到你看不到它,我想让它在屏幕右侧重新生成并移动。左边是工作,但右边不是。在屏幕右侧设置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

我会做类似下面按您的标准:

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

用来模仿你的游戏行为,基于一些猜测(因为你还没有表现出足够)以及您迄今提供的信息。

你的UFO现在飞我的屏幕上从右至左,回到正确的,根据您的标准:

- (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]; 
} 
+0

啊,我都尝试过,但它再次出现在屏幕左侧,而不是右侧,这是没有意义:( – Robin

+0

是啊,我复制你的,但它仍然是一样的错误:( – Robin

+0

我知道他们应该像这样重新出现在屏幕的权利,但他们不这没有任何意义。 – Robin

1

我假设你的backGround顶部增加ufo和尝试移动在定时器的帮助下,在背景视图之上从右到左的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; 
相关问题