//过期的加速计类UIAccelerometer是不需要引入系统框架的,
//CoreMotionManager 需要引入CoreMotion框架
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
#import "UIView+Extension.h"
#import "AudioTool.h"
@interface ViewController ()<UIAccelerometerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *ball;
//过期的加速计对象
@property(nonatomic,strong)UIAccelerometer*accelerometer;
@property(nonatomic,strong)CMMotionManager *manager;
//记录当前的速度 x轴 Y轴 的速度
@property(nonatomic,assign)CGPoint speed;
//保存上一次的坐标
@property(nonatomic,assign)CGPoint prePoint;
@end
@implementation ViewController
//懒加载创建运动管理器
-(CMMotionManager*)manager
{
if (!_manager) {
_manager=[[CMMotionManager alloc]init];
//设置加速计更新间隔
_manager.accelerometerUpdateInterval=1/30.0;
}
return _manager;
}
- (void)viewDidLoad {
[super viewDidLoad];
//motionManager有两种更新方式,一种是主动获取,需要时更新
//另一种是一直更新
//1.一直更新
[self.manager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
//获取加速度的结构体
CMAcceleration acceleration=accelerometerData.acceleration;
//acceleration.x,X轴上的加速度,acceleration.y,Y轴上的加速度
_speed.x+=acceleration.x;
_speed.y-=acceleration.y;
//移动小球
self.ball.x+=_speed.x;
self.ball.y=_speed.y;
//碰撞检测,是否触碰到了边界
if(self.ball.x<0)
{
self.ball.x=0;
_speed.x*=-0.8;
}
if (self.ball.x>self.view.width-self.ball.width) {
self.ball.x=self.view.width-self.ball.width;
_speed.x=-0.8;
}
if (self.ball.y < 0) {
self.ball.y = 0;
_speed.y *= -0.8;
}
if (self.ball.y > self.view.height - self.ball.height) {
self.ball.y = self.view.height - self.ball.height;
_speed.y *= -0.8;
}
if (self.ball.x != _prePoint.x && self.ball.y != _prePoint.y ) {
if (self.ball.x == 0 || self.ball.x == self.view.width - self.ball.width || self.ball.y == 0 || self.ball.y == self.view.height - self.ball.height) {
//播放音效
[AudioTool playWithFileName:@"1.aif"];
}
}
_prePoint.x = self.ball.x;
_prePoint.y = self.ball.y;
}];
}
//2.主动获取
-(void)test
{
//需要值的时候自己去拿
[self.manager startAccelerometerUpdates];
}
//点击屏幕获取
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//获取加速计的结构体
CMAcceleration acceleration=self.manager.accelerometerData.acceleration;
NSLog(@"x=%lf,y=%lf,z=%lf",acceleration.x,acceleration.y,acceleration.z);
}
//3 过期的加速计
-(void)testaddAccelerometer
{
//1.创建 加速计对象 UIAccelerometer 是一个系统自带单例
UIAccelerometer *accelero=[[UIAccelerometer alloc]init];
self.accelerometer=accelero;
//设置更新间隔
accelero.updateInterval=1/30;
accelero.delegate=self;
}
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
NSLog(@"x=%lf,y=%lf,z=%lf",acceleration.x,acceleration.y,acceleration.z);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
来源:https://www.cnblogs.com/tangranyang/p/4659532.html