加速计案例(小球移动) - (Obj-C)

实现方式:
使用加速计反应小球的受力情况,通过改变小球的frame,改变小球的位置

需要实时获取数据,所以要使用Push方式

这里只是根据加速度模拟小球移动:移动距离和加速度正相关

1.需要移动距离进行累加来表示移动距离的变化 受力移动时间越长,速度越大,移动距离越来越远

2.避免小球移出界面,判断小球的坐标,当X轴和Y轴坐标分表小于等于零和大于等于屏幕宽度/高度-自身宽度/高度时,先让小球的坐标值等于临界值,然后改变加速度方向

3.同时为了模拟移动时的阻力,系数乘以了0.8

示例代码:


#import "ViewController.h"
#import 

@interface ViewController ()
// 行为管理者
@property (nonatomic,strong) CMMotionManager *manager;
// 小球
@property (nonatomic,strong) UIImageView *ballImageView;
// 每次X轴移动的距离
@property (nonatomic,assign) CGFloat tmpAccelerationX;
// 每次Y轴移动的距离
@property (nonatomic,assign) CGFloat tmpAccelerationY;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建小球
    self.ballImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ball"]];
    self.ballImageView.bounds = CGRectMake(0, 0, 40, 40);
    [self.view addSubview:self.ballImageView];
    
    // 1. 创建管理者
    self.manager = [[CMMotionManager alloc]init];
    
    // 2. 设置间隔时间
    self.manager.accelerometerUpdateInterval = 0.02f;
    
    // 3. 开启检测
    [self.manager startAccelerometerUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMAccelerometerData * _Nullable accelerometerData, NSError * _Nullable error) {
        
        CMAcceleration acceleration = accelerometerData.acceleration;
        [self ballMoveWithAccelerometerData:acceleration];
        
    }];
    
}

// 小球移动
- (void)ballMoveWithAccelerometerData:(CMAcceleration)acceleration{
    
    CGRect ballFrame = self.ballImageView.frame;
    
    self.tmpAccelerationX += acceleration.x;
    self.tmpAccelerationY -= acceleration.y;
    
    ballFrame.origin.x += self.tmpAccelerationX;
    ballFrame.origin.y += self.tmpAccelerationY;
    
    
    // 判断X轴、Y轴坐标,避免小球移出屏幕
    if (ballFrame.origin.x >= [UIScreen mainScreen].bounds.size.width - self.ballImageView.bounds.size.width) {
        
        ballFrame.origin.x = [UIScreen mainScreen].bounds.size.width - self.ballImageView.bounds.size.width;
        self.tmpAccelerationX *= -0.8;
        
    } else if (ballFrame.origin.x <= 0){
        
        ballFrame.origin.x = 0;
        self.tmpAccelerationX *= -0.8;
        
    }
    
    if (ballFrame.origin.y >= [UIScreen mainScreen].bounds.size.height - self.ballImageView.bounds.size.height){
        
        ballFrame.origin.y = [UIScreen mainScreen].bounds.size.height - self.ballImageView.bounds.size.height;
        self.tmpAccelerationY *= -0.8;
        
    }else if (ballFrame.origin.y <= 0){
        
        ballFrame.origin.y = 0;
        self.tmpAccelerationY *= -0.8;
    }
    
    self.ballImageView.frame = ballFrame;
}

@end

你可能感兴趣的:(加速计案例(小球移动) - (Obj-C))