iOS基础-加速器使用2(小球乱撞)

加速器使用注意:

UIAccelerometer使用:

  1. 单例创建
  2. 设置代理
  3. 设置采样间隔

注:手机呈肖像模式时,


iOS基础-加速器使用2(小球乱撞)_第1张图片
Snip20150331_1.png
@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *ball;
@property (nonatomic, assign) CGPoint point;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
//    单例创建
    UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
//    设置代理
    accelerometer.delegate = self;

//    设置采样间隔 -- 每秒钟60次
    accelerometer.updateInterval = 1 / 60.0;
}

#pragma mark - UIAccelerometerDelegate
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    NSLog(@"x - %f y - %f z - %f",acceleration.x, acceleration.y, acceleration.z);
    _point.x += acceleration.x;
    _point.y -= acceleration.y;

    CGRect rect = self.ball.frame;
    rect.origin.x += acceleration.x;
    rect.origin.y += acceleration.y;

    self.ball.frame = rect;

    if (self.ball.frame.origin.x <= 0) { // 小球x值到达屏幕最左边
        self.ball.x = 0;
        _point.x *= -0.3;
    }
    if (self.ball.frame.origin.y <= 0) { // 小球y值到达屏幕最上边
        self.ball.y = 0;
        _point.y *= -0.3;
    }
    if (CGRectGetWidth(self.ball.frame) >= self.view.width) { // 小球x值到达屏幕最右边
        self.ball.x = self.view.width - self.ball.width;
        _point.x *= -0.3;
    }
    if (CGRectGetHeight(self.ball.frame) >= self.view.height) { // 小球y值到达屏幕最下边
        self.ball.y = self.view.height = self.ball.height;
        _point.y *= -0.3;
    }
}

你可能感兴趣的:(iOS基础-加速器使用2(小球乱撞))