主要功能描述:页面中的小球可以根据手机倾斜的方向做运动
运用的知识:加速计、UIDynamic物理仿真行为
具体代码:
#import "ViewController.h"
@interface ViewController ()<UIAccelerometerDelegate>
@property (strong, nonatomic) IBOutlet UIView *redView;
@property (weak, nonatomic) IBOutlet UIView *grayView;
@property (weak, nonatomic) IBOutlet UIView *blueView;
@property (strong, nonatomic) UIDynamicAnimator *animator;
@property (strong, nonatomic) UIGravityBehavior *gravity;
@end
@implementation ViewController
- (UIDynamicAnimator *)animator {
if (_animator == nil) {
_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
}
return _animator;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.redView.layer.cornerRadius = 25;
self.redView.layer.masksToBounds = YES;
self.grayView.layer.cornerRadius = 25;
self.grayView.layer.masksToBounds = YES;
self.blueView.layer.cornerRadius = 25;
self.blueView.layer.masksToBounds = YES;
//获得单例对象
UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
//设置代理
accelerometer.delegate = self;
//设置采样间隔 0.1
accelerometer.updateInterval = 0.1;
[self testGravity];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
{
// NSLog(@"x加速度%f**********y加速度%f*******z加速度%f",acceleration.x,acceleration.y,acceleration.z);
self.gravity.gravityDirection = CGVectorMake(acceleration.x-0.1, -(acceleration.y-0.1));
}
/// 设置重力行为
- (void)testGravity {
// 1.创建仿真行为(进行怎样的仿真效果?)
// 重力行为
self.gravity = [[UIGravityBehavior alloc] initWithItems:@[self.redView,self.grayView,self.blueView]];
self.gravity.magnitude = 10;
// 2.添加物理仿真元素
// [self.gravity addItem:self.redView];
/// 添加碰撞检测行为
UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.redView,self.grayView,self.blueView]];
// 添加碰撞边界
collision.translatesReferenceBoundsIntoBoundary = YES;
UIDynamicItemBehavior *itemBehave = [[UIDynamicItemBehavior alloc] initWithItems:@[self.redView,self.grayView,self.blueView]];
/// 弹性系数
itemBehave.elasticity = 0.4;
// 3. 执行仿真,让物理仿真元素执行仿真行为
[self.animator addBehavior:self.gravity];
[self.animator addBehavior:collision];
[self.animator addBehavior:itemBehave];
}
@end
网友评论