【手机平台项目学习和分析】NSTimer 类的学习:遇到屏幕边返回的小球

1.我们先来看看效果和初始情况



2.大致来说,我们就是通过改变switch的值,改变球的移动速度

1)碰撞检测 onTimer方法

- (void)onTimer
{
    self.imageView.center = CGPointMake(self.imageView.center.x + delta.x, self.imageView.center.y +delta.y);  //设置当前球的中心。
//反弹操作
    if (self.imageView.center.x > self.view.bounds.size.width - ballRadius || self.imageView.center.x <ballRadius) {
        delta.x = -delta.x;
    }
    
    if (self.imageView.center.y > self.view.bounds.size.height - ballRadius || self.imageView.center.y <ballRadius) {
        delta.y = -delta.y;
    }
}

2)viewDidLoad方法

- (void)viewDidLoad
{
    [super viewDidLoad];
    ballRadius = self.imageView.bounds.size.width/2;
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    delta = CGPointMake(12.0, 5.0);
    
    timer = [NSTimer scheduledTimerWithTimeInterval:slider.value target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    
	// Do any additional setup after loading the view, typically from a nib.
}

3.改变switch之后进行相应的改变

- (IBAction)sliderMoved:(id)sender {
    
    self.label.text = [NSString stringWithFormat:@"%f",slider.value];
    
    [timer invalidate];  //停止当前NStimer的活动
    timer = [NSTimer scheduledTimerWithTimeInterval:slider.value target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值