您好,欢迎来到二三四教育网。
搜索
您的当前位置:首页摩拜贴纸的仿真动画以及传感器

摩拜贴纸的仿真动画以及传感器

来源:二三四教育网

先看看摩拜贴纸的动画:

知识点归纳:

  • 使用重力行为
  • 使用碰撞行为
  • 使用弹力行为
  • 使用屏幕旋转的传感器

代码实现:

  1. 创建若干个小球(UIImageView)
    NSMutableArray *ballViewArr = [NSMutableArray array];
    for(int i=0;i<imageArr.count;i++)
    {
        UIImageView * imgView = [[UIImageView alloc]initWithFrame:CGRectMake(arc4random()%((int)(self.view.bounds.size.width-diameter)), 0, diameter, diameter)];
        imgView.image = [UIImage imageNamed:imageArr[i]];
        imgView.layer.masksToBounds = YES;
        imgView.layer.cornerRadius = diameter/2;
        [self.view addSubview:imgView];
        
        [ballViewArr addObject:imgView];
    }

2.创建动画的播放者

    //_animator为全局定义的,否则不会生效,self.view为力学参考系,动力效果才能生效
    _animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];

3.创建动力行为,并赋给小球

    //添加重力
    _gravity = [[UIGravityBehavior alloc]initWithItems:ballViewArr];
    [_animator addBehavior:_gravity];
    
    //添加碰撞
    UICollisionBehavior *collision = [[UICollisionBehavior alloc]initWithItems:ballViewArr];
    collision.translatesReferenceBoundsIntoBoundary = YES;
    [_animator addBehavior:collision];
    
    //添加弹性
    UIDynamicItemBehavior *dyItem = [[UIDynamicItemBehavior alloc]initWithItems:ballViewArr];
    dyItem.allowsRotation = YES;
    dyItem.elasticity = 0.8;        //弹性系数
    [_animator addBehavior:dyItem];
    
    //还有很多behavior:UIAttachmentBehavior(附着行为)、UISnapBehavior(捕捉行为)、UIPushBehavior(推动行为)、UIDynamicItemBehavior(动力元素行为)

4.创建检测屏幕旋转的传感器,并计算新的弧度给重力行为属性赋值

-(void)initGyroManager
{
    self.motionManager = [[CMMotionManager alloc]init];
    self.motionManager.deviceMotionUpdateInterval = 0.01;
    
    [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
        //返回至原点的方位角
        double rotation = atan2(motion.attitude.pitch, motion.attitude.roll);
        NSLog(@"rotation:%f",motion.attitude.pitch);
        self.gravity.angle = rotation;
    }];
}
-(void)dealloc
{
    [self.motionManager stopDeviceMotionUpdates];
}

Copyright © 2019- how234.cn 版权所有 赣ICP备2023008801号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务