UIDynamic-iOS中的物理引擎

UIDynamic-iOS中的物理引擎

  1. 創(chuàng)建一個物理仿真器 設(shè)置仿真范圍
  2. 創(chuàng)建相應(yīng)的物理仿真行為 添加物理仿真元素
  3. 將物理仿真行為添加到仿真器中開始仿真

懶加載方式 創(chuàng)建物理仿真器

-  (UIDynamicAnimator *) animator
{
if(!_animator) {
_animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
}
return _animator;
}

創(chuàng)建相應(yīng)的物理仿真行為

  1. 模擬重力行為 UIGravityBehavior
    // 創(chuàng)建重力行為
    UIGravityBehavior *gravity = [[UIGravityBehavior alloc] init];
    // magnitude越大,速度增長越快
    gravity.magnitude = 100;
    // 添加元素 告訴仿真器哪些元素添加重力行為
    [gravity addItem:self.sxView];

    // 添加到仿真器中開始仿真
    [self.animator addBehavior:gravity];

  2. 模擬碰撞行為 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];

  3. 模擬捕捉行為 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];
      }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容