加速传感器

P:由于硬件相关的都封装好了,比较简单,这里直接介绍方法

步骤:

      1、获得单例对象:UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];

   2、设置代理:accelerometer.delegate = self;

   3、设置采样间隔:accelerometer.updateInterval = 1.0/30.0; // 1秒钟采样30

   4、实现代理方法:- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration

// acceleration中的xyz三个属性分别代表每个轴上的加速度

代码:

#import "ViewController.h"
#import "UIView+AdjustFrame.h" // 一个分类,用来直接取width,height等

@interface ViewController () <UIAccelerometerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *ball;

// 保留x,y轴上面的速度
@property(nonatomic,assign)CGPoint velocity;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 1.获取单例对象
    UIAccelerometer *acclerometer = [UIAccelerometer sharedAccelerometer];
    
    // 2.设置代理
    acclerometer.delegate = self;
    
    // 3.设置采样间隔
    acclerometer.updateInterval = 1 / 30.0;
}

/**
 *  获取到加速计信息的时候会调用该方法
 *
 *  @param acceleration  里面有x,y,z抽上面的加速度
 */
- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
    // NSLog(@"x:%f y:%f z:%f", acceleration.x, acceleration.y, acceleration.z);
    // 1.计算小球速度(对象的结构内部的属性是不能直接赋值)
    _velocity.x += acceleration.x;
    _velocity.y += acceleration.y;
    
    // 2.让小球移动
    /*
    CGRect ballFrame = self.ball.frame;
    ballFrame.origin.x += _velocity.x;
    self.ball.frame = ballFrame;
     */
    self.ball.x += _velocity.x;
    self.ball.y -= _velocity.y;
    
    // 3.边界判断
    if (self.ball.x <= 0) {
        self.ball.x = 0;
        _velocity.x *= -0.6;
    }
    if (self.ball.x >= self.view.width - self.ball.width) {
        self.ball.x = self.view.width - self.ball.width;
        _velocity.x *= -0.6;
    }
    if (self.ball.y <= 0) {
        self.ball.y = 0;
        _velocity.y *= -0.6;
    }
    if (self.ball.y >= self.view.height - self.ball.height) {
        self.ball.y = self.view.height - self.ball.height;
        _velocity.y *= -0.6;
    }
    
    NSLog(@"x:%f y:%f", _velocity.x, _velocity.y);
}

由于是真机调试,没有截图,效果是跳来跳去

原文地址:https://www.cnblogs.com/10-19-92/p/4979990.html