UIDynamic-iOS中的物理引擎

作者: Nirvana_icy | 来源:发表于2015-03-31 14:37 被阅读1649次

    UIDynamic-iOS中的物理引擎

    1. 创建一个物理仿真器 设置仿真范围
    2. 创建相应的物理仿真行为 添加物理仿真元素
    3. 将物理仿真行为添加到仿真器中开始仿真

    懒加载方式 创建物理仿真器

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

    创建相应的物理仿真行为

    1. 模拟重力行为 UIGravityBehavior
      // 创建重力行为
      UIGravityBehavior *gravity = [[UIGravityBehavior alloc] init];
      // magnitude越大,速度增长越快
      gravity.magnitude = 100;
      // 添加元素 告诉仿真器哪些元素添加重力行为
      [gravity addItem:self.sxView];

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

    2. 模拟碰撞行为 UICollisionBehavior
      // 1.创建重力行为
      UIGravityBehavior *gravity = [[UIGravityBehavior alloc] init];
      // magnitude越大,速度增长越快
      gravity.magnitude = 2;
      [gravity addItem:self.sxView];

      // 2.创建碰撞行为
      UICollisionBehavior *collision = [[UICollisionBehavior alloc] init];
      [collision addItem:self.sxView];
      [collision addItem:self.bigBlock];
      [collision addItem:self.smallBlock];
      // 设置碰撞的边界
      collision.translatesReferenceBoundsIntoBoundary = YES;
      // 如果觉得屏幕作为边界不好,可以自己设置一条边可以是普通的边
      // [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.获得手指对应的触摸对象
        UITouch *touch = [touches anyObject];

        // 2.获得触摸点
        CGPoint point = [touch locationInView:self.view];

        // 3.创建捕捉行为
        UISnapBehavior *snap = [[UISnapBehavior alloc] initWithItem:self.sxView snapToPoint:point];
        // 防震系数,damping越大,振幅越小
        snap.damping = 1;

        // 4.清空之前的并再次开始
        [self.animator removeAllBehaviors];
        [self.animator addBehavior:snap];
        }

    相关文章

      网友评论

        本文标题:UIDynamic-iOS中的物理引擎

        本文链接:https://www.haomeiwen.com/subject/nxloxttx.html