加速计的作用
--用于监测设备的运动(比如摇晃)
--加速计的经典应用场景(摇一摇,计步器)
--加速计的原理:监测设备在X,Y,Z轴上的加速度(那个方向有力的作用,那个方向运动了)
加速计的程序开发史
1.在iOS4以前,使用UIAccelerometer,用法非常简单(到了iOS5就已经过期啦)
2.从iOS4开始: CoreMotion.frameWork
UIAccelerometer的使用步骤
1.获得单利对象
2.设置代理
3.设置采样间隔
4.实现代理方法
代码
//
// ViewController.m
// 加速计
//
// Created by ws on 2017/6/13.
// Copyright © 2017年 王松. All rights reserved.
//
#import "ViewController.h"
///遵循协议
@interface ViewController ()<UIAccelerometerDelegate>
///创建一个小球
@property (strong, nonatomic) IBOutlet UIImageView *redImageView;
///保留x,y轴上面的速度
@property(nonatomic,assign)CGPoint velocity;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.redImageView.layer.cornerRadius = 50/2;
self.redImageView.layer.masksToBounds = YES;
//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(@"%f__%f__%f",acceleration.x,acceleration.y,acceleration.z);
//1.计算小球的速度(对象的结构体每部的属性(self.velocity)是不能直接赋值的,成员变量可以(_velocity))
_velocity.x += acceleration.x;
_velocity.y -= acceleration.y;
//2.让小球移动
CGRect ballFrame = self.redImageView.frame;
ballFrame.origin.x += _velocity.x;
ballFrame.origin.y += _velocity.y;
self.redImageView.frame = ballFrame;
#warning 一下是具体的逻辑代码,依据实际开发而定
//3.边界判断
if (self.redImageView.frame.origin.x <= 0) {
CGRect leftFrame = self.redImageView.frame;
leftFrame.origin.x = 1;
self.redImageView.frame = leftFrame;
_velocity.x *= -0.6;
}
if (self.redImageView.frame.origin.x >= self.view.bounds.size.width - self.redImageView.frame.size.width){
CGRect leftFrame = self.redImageView.frame;
leftFrame.origin.x = self.view.bounds.size.width - self.redImageView.frame.size.width - 1;
self.redImageView.frame = leftFrame;
_velocity.x *= -0.6;
}
if (self.redImageView.frame.origin.y <= 0){
CGRect leftFrame = self.redImageView.frame;
leftFrame.origin.y = 1;
self.redImageView.frame = leftFrame;
_velocity.y *= -0.6;
}
if (self.redImageView.frame.origin.y >= self.view.bounds.size.height - self.redImageView.frame.size.height){
CGRect leftFrame = self.redImageView.frame;
leftFrame.origin.y = self.view.bounds.size.height - self.redImageView.frame.size.height - 1;
self.redImageView.frame = leftFrame;
_velocity.y *= -0.6;
}
}
@end