加速器使用注意:
UIAccelerometer使用:
- 單例創(chuàng)建
- 設(shè)置代理
- 設(shè)置采樣間隔
注:手機呈肖像模式時夫椭,
@interface ViewController ()<UIAccelerometerDelegate]] >
@property (weak, nonatomic) IBOutlet UIImageView *ball;
@property (nonatomic, assign) CGPoint point;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// 單例創(chuàng)建
UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
// 設(shè)置代理
accelerometer.delegate = self;
// 設(shè)置采樣間隔 -- 每秒鐘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;
}
}