1.捕捉
@interfaceViewController ()
//声明仿真器属性 保命啊
@property(nonatomic,strong)UIDynamicAnimator *animator;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@end
@implementation ViewController
//物理仿真器懒加载
-(UIDynamicAnimator *)animator{
if (!_animator) {
//1.创建物理仿真器 指定仿真范围
_animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
}
return _animator;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//在添加行为之前 先移除上次的行为
[self.animator removeAllBehaviors];
//获取捕捉的点
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:touch.view];
//2.创建捕捉行为 指定元素
UISnapBehavior *snap = [[UISnapBehavior alloc]initWithItem:self.imageView snapToPoint:point];
//减震 随机系数
snap.damping = arc4random_uniform(100)/100.0;
//3.添加到物理仿真器中
[self.animator addBehavior:snap];
}
2.重力 碰撞
- (void)viewDidLoad {
[super viewDidLoad];
// 1.创建物理仿真器 顺便指定仿真范围
UIDynamicAnimator *animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
//需要保命啊
self.animator = animator;
//2.创建重力仿真行为 指定仿真元素
UIGravityBehavior *gravity = [[UIGravityBehavior alloc]initWithItems:@[self.blueView]];
//3.将行为添加到物理仿真器中
[self.animator addBehavior:gravity];
//给one two 添加碰撞行为
//1.创建碰撞仿真行为 指定仿真元素
UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.one,self.two,self.blueView]];
//边界
collision.translatesReferenceBoundsIntoBoundary = YES;
//2.将碰撞行为也添加到物理仿真器中
[self.animator addBehavior:collision];
}