2015-08-21 55 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; 
相關問題