美文网首页
iOS CoreMotion重力感应

iOS CoreMotion重力感应

作者: 倪大头 | 来源:发表于2018-05-10 14:56 被阅读14次

    系统提供CMMotionManager获取感应数据,startDeviceMotionUpdatesToQueue方法被动获取数据,可以设置采集数据的间隔

    #import "CoreMotionViewController.h"
    #import <CoreMotion/CoreMotion.h>
    
    @interface CoreMotionViewController ()
    
    @property (nonatomic, strong)CMMotionManager *motionManager;
    
    @property (nonatomic, strong)UIImageView *carImg;
    
    @property (nonatomic, strong)UIImageView *roadView;
    
    @end
    
    @implementation CoreMotionViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        // Do any additional setup after loading the view.
        
        [self setCoreMotionManager];
    }
    
    - (void)setCoreMotionManager {
        self.roadView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_SCREEN_HEIGHT)];
        self.roadView.center = self.view.center;
        self.roadView.image = [UIImage imageNamed:@"road"];
        self.roadView.contentMode = UIViewContentModeScaleAspectFill;
        self.roadView.clipsToBounds = YES;
        [self.view addSubview:self.roadView];
        
        self.carImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, kScaleX*64, kScaleY*64)];
        self.carImg.image = [UIImage imageNamed:@"car"];
        self.carImg.center = CGPointMake(self.view.frame.size.width/2, self.view.frame.size.height - kScaleY*30 - self.carImg.frame.size.height/2);
        [self.roadView addSubview:self.carImg];
        
        self.motionManager = [[CMMotionManager alloc]init];
        self.motionManager.deviceMotionUpdateInterval = 1/5;//设置采样间隔
    
        [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
            //根据motion.attitude.roll调整小车位置
            [self moveCarWithMotionRoll:motion.attitude.roll];
        }];
    }
    
    - (void)moveCarWithMotionRoll:(CGFloat)roll {
        [UIView animateWithDuration:0.2 animations:^{
            if (roll < 0) {
                self.carImg.center = CGPointMake(self.roadView.frame.size.width/4, self.carImg.center.y);
            }else {
                self.carImg.center = CGPointMake(self.roadView.frame.size.width/4*3, self.carImg.center.y);
            }
        }];
    }
    
    WechatIMG10.png

    相关文章

      网友评论

          本文标题:iOS CoreMotion重力感应

          本文链接:https://www.haomeiwen.com/subject/vbwzrftx.html