![](https://img.haomeiwen.com/i792843/a7bef9869d6505e1.gif)
获取设备的重力感应,就需要导入系统的核心库
#import <CoreMotion/CoreMotion.h>
// 设备运动服务管理者
@property (nonatomic, strong) CMMotionManager *manager;
- 创建运动管理者,模拟设备的重力感应
_manager = [[CMMotionManager alloc] init];
// 设置更新精度
_manager.deviceMotionUpdateInterval = 0.01;
2.创建一个物理仿真器,(顺便设置仿真范围)
_animtor = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
3.创建重力仿真行为
_gryBehvior = [[UIGravityBehavior alloc] initWithItems:@[]];
_gryBehvior.gravityDirection = CGVectorMake(0.0, 1.0);
4.创建物理碰撞仿真行为, 让参照视图的边框成为碰撞检测的边界
_clnBehavior = [[UICollisionBehavior alloc] initWithItems:@[]];
_clnBehavior.translatesReferenceBoundsIntoBoundary = YES;
_clnBehavior.collisionDelegate = self;
5.将仿真行为添加到物理仿真器中开始仿真
//将重力仿真行为添加到物理仿真器中开始仿真
[self.animtor addBehavior:_gryBehvior];
//将碰撞仿真行为添加到物理仿真器中开始仿真
[self.animtor addBehavior:_clnBehavior];
- 创建仿真元素, 仿真行为添加仿真元素
UIImageView *img = [[UIImageView alloc] initWithImage:[NSString stringWithFormat:@"1"]];
[self.gryBehvior addItem: img];
[self.clnBehavior addItem: img];
7.最重要的一步,监听设备重力感应变化,并改变重力行为的重力方向
[self.manager startDeviceMotionUpdatesToQueue:NSOperationQueue.mainQueue withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
// 设置重力方向
self.gryBehvior.gravityDirection = CGVectorMake(motion.gravity.x, -motion.gravity.y);
}];
demo奉上
各位看官,喜欢的留个爪!
日常记录,分享交流,不喜勿喷!
网友评论