属性分析:
1 @property (nonatomic, readonly, copy) NSArray* items; 2 3 @property (readwrite, nonatomic) CGFloat elasticity; // Usually between 0 (inelastic) and 1 (collide elastically) 弹性系数 在0~1之间 4 @property (readwrite, nonatomic) CGFloat friction; // 0 being no friction between objects slide along each other 摩擦力系数 5 @property (readwrite, nonatomic) CGFloat density; // 1 by default 跟size大小相关,计算物体块的质量。 6 @property (readwrite, nonatomic) CGFloat resistance; // 0: no velocity damping 阻力系数 7 @property (readwrite, nonatomic) CGFloat angularResistance; // 0: no angular velocity damping 旋转阻力 8 @property (readwrite, nonatomic) BOOL allowsRotation; // force an item to never rotate 是否能旋转
代码:
1 // 2 // YFDynamicItemViewController.m 3 // BigShow1949 4 // 5 // Created by apple on 16/8/25. 6 // Copyright © 2016年 BigShowCompany. All rights reserved. 7 // 8 9 #import "YFDynamicItemViewController.h" 10 11 @interface YFDynamicItemViewController () 12 @property(nonatomic,strong)UIDynamicAnimator *animator; 13 @property (nonatomic, strong) UIView *redView; 14 15 16 @end 17 18 @implementation YFDynamicItemViewController 19 20 - (void)viewDidLoad { 21 22 [super viewDidLoad]; 23 self.view.backgroundColor = [UIColor whiteColor]; 24 25 26 UIView *redView = [[UIView alloc] init]; 27 redView.frame = CGRectMake(100, 100, 100, 100); 28 redView.backgroundColor = [UIColor redColor]; 29 self.redView = redView; 30 [self.view addSubview:redView]; 31 } 32 33 34 35 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { 36 37 [self testGravityAndCollsion]; 38 } 39 /** 40 * 重力行为+碰撞检测 41 */ 42 -(void)testGravityAndCollsion 43 { 44 //1.重力行为 45 UIGravityBehavior *gravity=[[UIGravityBehavior alloc]init]; 46 [gravity addItem:self.redView]; 47 48 //2碰撞检测行为 49 UICollisionBehavior *collision=[[UICollisionBehavior alloc]init]; 50 [collision addItem:self.redView]; 51 //让参照视图的边框成为碰撞检测的边界 52 collision.translatesReferenceBoundsIntoBoundary=YES; 53 54 // 动力元素行为 55 UIDynamicItemBehavior * itemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[self.redView]]; 56 itemBehavior.elasticity = 1.2; 57 itemBehavior.friction = 1.; 58 itemBehavior.density = 1; 59 itemBehavior.resistance = 3; // 阻力系数 60 itemBehavior.allowsRotation = NO; 61 itemBehavior.angularResistance = 1; 62 63 //3.执行仿真 64 [self.animator addBehavior:gravity]; 65 [self.animator addBehavior:collision]; 66 [self.animator addBehavior:itemBehavior]; 67 } 68 69 70 -(UIDynamicAnimator *)animator 71 { 72 if (_animator==nil) { 73 //创建物理仿真器(ReferenceView:参照视图,设置仿真范围) 74 self.animator=[[UIDynamicAnimator alloc]initWithReferenceView:self.view]; 75 } 76 return _animator; 77 } 78 79 80 @end