2009-12-05 91 views
0

我想跳在視圖中的特定領域的球, 問題是,我不知道如何定義這個領域的領域和運動的位置。 也 這裏是我用來在整個視圖中移動球的代碼(球對象是視圖上的uiimageview)。 謝謝。iPhone開發-CGPoint&NSTimer幫助

- (void)onTimer {ballIcenter = CGPointMake(ball.center.x + pos.x,ball.center.y + pos.y);

if(ball.center.x > 320 || ball.center.x < 0) 
    pos.x = -pos.x; 
if(ball.center.y > 460 || ball.center.y < 0) 
    pos.y = -pos.y; 

}

//實現viewDidLoad中加載視圖後做額外的設置。 - (void)viewDidLoad pos = CGPointMake(14.0,7.0);

[NSTimer scheduledTimerWithTimeInterval:0.03 target:self selector:@selector(onTimer) userInfo:nil repeats:YES]; 

}

+0

您需要澄清您的問題和/或將其分解爲多個部分。你現在的代碼有什麼問題,即你看到了什麼意外的行爲?例如球根本不動嗎?他們移動但移動不正確?計時器是否不調用'onTimer:'方法? – TechZen 2009-12-05 16:20:59

+0

在上面的代碼中工作正常(球在整個屏幕中移動),但問題是我不能在視圖中的特定位置而不是320 \ 460中定義一個小區域。當我改變球的位置時,球會彈跳或移動到錯誤的位置。 – omri 2009-12-05 17:12:19

回答

0

而不是硬編碼的320和460,可以使用視圖的邊界,以獲得在其中你的球應該移動。

檢查出UIViewbounds財產。

+0

謝謝,我會檢查出來。 – omri 2009-12-05 17:13:08

0
@implementation ViewController { 
    BOOL isPositiveXAxis; 
    BOOL isPositiveYAxis; 
} 


- (void)viewDidLoad { 
    [super viewDidLoad]; 

    //By default we are setting both BOOL value to YES because ballImage have (0,0) origin by default 
    isPositiveXAxis = YES; 
    isPositiveYAxis = YES; 
    imgBallView.layer.cornerRadius = imgBallView.frame.size.width/2; 

    [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(animateBall) userInfo:nil repeats:YES]; 
} 

-(void)animateBall { 

     //getting current image transform, and we will modify it later in code 
     CGAffineTransform transform = imgBallView.transform; 


     //checking if ‘isPositiveXAxis is true and imgBallView xAxis have less value then view border 
     if (isPositiveXAxis && imgBallView.frame.origin.x < self.view.frame.size.width - imgBallView.frame.size.width) { 
      transform.tx++; 
     } 
     else { 
      isPositiveXAxis = NO; 

      if (transform.tx>0) { 
       transform.tx--; 
      } 
      else { 
       isPositiveXAxis = YES; 
      } 
     } 

     //checking if ‘isPositiveYAxis is true and imgBallView yAxis have less value then view border 
     if (isPositiveYAxis && imgBallView.frame.origin.y < self.view.frame.size.height - imgBallView.frame.size.height) { 
      transform.ty++; 
     } 
     else { 
      isPositiveYAxis = NO; 

      if (transform.ty>0) { 
       transform.ty--; 
      } 
      else { 
       isPositiveYAxis = YES; 
      } 
     } 

     //setting updated trasform to imgBallView it will look animated. 
     imgBallView.transform = transform; 
} 

上述代碼將生成所需的模式。在視頻中可以看到:https://vid.me/G3zO,這可能會幫助您更好地理解它