UIDynamic-iOS中的物理引擎
- 創(chuàng)建一個物理仿真器 設(shè)置仿真范圍
- 創(chuàng)建相應(yīng)的物理仿真行為 添加物理仿真元素
- 將物理仿真行為添加到仿真器中開始仿真
懶加載方式 創(chuàng)建物理仿真器
- (UIDynamicAnimator *) animator
{
if(!_animator) {
_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
}
return _animator;
}
創(chuàng)建相應(yīng)的物理仿真行為
-
模擬重力行為 UIGravityBehavior
// 創(chuàng)建重力行為
UIGravityBehavior *gravity = [[UIGravityBehavior alloc] init];
// magnitude越大,速度增長越快
gravity.magnitude = 100;
// 添加元素 告訴仿真器哪些元素添加重力行為
[gravity addItem:self.sxView];// 添加到仿真器中開始仿真
[self.animator addBehavior:gravity]; -
模擬碰撞行為 UICollisionBehavior
// 1.創(chuàng)建重力行為
UIGravityBehavior *gravity = [[UIGravityBehavior alloc] init];
// magnitude越大,速度增長越快
gravity.magnitude = 2;
[gravity addItem:self.sxView];// 2.創(chuàng)建碰撞行為
UICollisionBehavior *collision = [[UICollisionBehavior alloc] init];
[collision addItem:self.sxView];
[collision addItem:self.bigBlock];
[collision addItem:self.smallBlock];
// 設(shè)置碰撞的邊界
collision.translatesReferenceBoundsIntoBoundary = YES;
// 如果覺得屏幕作為邊界不好,可以自己設(shè)置一條邊可以是普通的邊
// [collision addBoundaryWithIdentifier:@"line2" fromPoint:
CGPointMake(self.view.frame.size.width, 0) toPoint:
CGPointMake(self.view.frame.size.width, 400)];
//也可以是個貝塞爾路徑
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:
CGRectMake(0,150, self.view.frame.size.width, self.view.frame.size.width)];
[collision addBoundaryWithIdentifier:@"circle" forPath:path];
// 3.開始仿真
[self.animator addBehavior:gravity];
[self.animator addBehavior:collision]; -
模擬捕捉行為 UISnapBehavior
-
(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
// 1.獲得手指對應(yīng)的觸摸對象
UITouch *touch = [touches anyObject];// 2.獲得觸摸點
CGPoint point = [touch locationInView:self.view];// 3.創(chuàng)建捕捉行為
UISnapBehavior *snap = [[UISnapBehavior alloc] initWithItem:self.sxView snapToPoint:point];
// 防震系數(shù),damping越大,振幅越小
snap.damping = 1;// 4.清空之前的并再次開始
[self.animator removeAllBehaviors];
[self.animator addBehavior:snap];
}
-