實現(xiàn)方式:
使用加速計反應(yīng)小球的受力情況,通過改變小球的frame,改變小球的位置
需要實時獲取數(shù)據(jù),所以要使用Push方式
這里只是根據(jù)加速度模擬小球移動:移動距離和加速度正相關(guān)
1.需要移動距離進(jìn)行累加來表示移動距離的變化 受力移動時間越長,速度越大,移動距離越來越遠(yuǎn)
2.避免小球移出界面,判斷小球的坐標(biāo),當(dāng)X軸和Y軸坐標(biāo)分表小于等于零和大于等于屏幕寬度/高度-自身寬度/高度時,先讓小球的坐標(biāo)值等于臨界值,然后改變加速度方向
3.同時為了模擬移動時的阻力,系數(shù)乘以了0.8
示例代碼:
#import "ViewController.h"
#import <CoreMotion/CoreMotion.h>
@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];
// 創(chuàng)建小球
self.ballImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"ball"]];
self.ballImageView.bounds = CGRectMake(0, 0, 40, 40);
[self.view addSubview:self.ballImageView];
// 1. 創(chuàng)建管理者
self.manager = [[CMMotionManager alloc]init];
// 2. 設(shè)置間隔時間
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軸坐標(biāo),避免小球移出屏幕
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