2009-12-05 69 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,这可能会帮助您更好地理解它