标签:
//UIDynamicAnimator :动态仿真
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *rectGreen;
@property (weak, nonatomic) IBOutlet UIView *rectBlue;
//创建仿真类
@property(nonatomic,strong)UIDynamicAnimator *animator;
@end
@implementation ViewController
//懒加载创建物理仿真类
-(UIDynamicAnimator*)animator
{
//1.创建仿真器指定仿真范围
if (!_animator) {
_animator=[[UIDynamicAnimator alloc]initWithReferenceView:self.view];
}
return _animator;
}
- (void)viewDidLoad {
[super viewDidLoad];
//2创建仿真行为(重力),指定仿真元素
UIGravityBehavior *gravity=[[UIGravityBehavior alloc]initWithItems:@[self.rectGreen]];
//量级
gravity.magnitude=2;
//3添加仿真行为到仿真器
[self.animator addBehavior:gravity];
//4创建碰撞行为
UICollisionBehavior *collision=[[UICollisionBehavior alloc]initWithItems:@[self.rectGreen,self.rectBlue] ];
//设置碰撞边界
collision.translatesReferenceBoundsIntoBoundary=YES;
//开始仿真
[self.animator addBehavior:collision];
// UIGravityBehavior *blue=[[UIGravityBehavior alloc]initWithItems:@[self.rectBlue]];
// //量级
// blue.magnitude=0.1;
// //3添加仿真行为到仿真器
// [self.animator addBehavior:blue];
}
//扑捉行为
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//可以移除之前的所有行为
//[self.animator removeAllBehaviors];
//获得点击的坐标
UITouch *touch=[touches anyObject];
CGPoint point=[touch locationInView:touch.view];
//创建捕捉行为
UISnapBehavior *snap=[[UISnapBehavior alloc]initWithItem:self.rectBlue snapToPoint:point];
//设置减震属性
snap.damping=arc4random_uniform(100)/100.0;
//添加开始仿真
[self.animator addBehavior:snap];
}
@end
标签:
原文地址:http://www.cnblogs.com/tangranyang/p/4659528.html