摩拜貼紙的仿真動畫以及傳感器

先看看摩拜貼紙的動畫:

知識點(diǎn)歸納:

  • 使用重力行為
  • 使用碰撞行為
  • 使用彈力行為
  • 使用屏幕旋轉(zhuǎn)的傳感器

代碼實(shí)現(xiàn):

  1. 創(chuàng)建若干個小球(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.創(chuàng)建動畫的播放者

    //_animator為全局定義的,否則不會生效,self.view為力學(xué)參考系,動力效果才能生效
    _animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];

3.創(chuàng)建動力行為,并賦給小球

    //添加重力
    _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;        //彈性系數(shù)
    [_animator addBehavior:dyItem];
    
    //還有很多behavior:UIAttachmentBehavior(附著行為)、UISnapBehavior(捕捉行為)、UIPushBehavior(推動行為)、UIDynamicItemBehavior(動力元素行為)

4.創(chuàng)建檢測屏幕旋轉(zhuǎn)的傳感器,并計(jì)算新的弧度給重力行為屬性賦值

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

這樣,代碼就搞定咯。另外可以參考:iOS進(jìn)階 - UIDynamic以及iOS的一些傳感器

此篇博客的Demo地址

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

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

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,229評論 4 61
  • 有點(diǎn)猶豫要不要分享這個地方。我為了寫游記回頭做行程表的時(shí)候(去年出游的時(shí)候說走就走,什么功課都沒做),這個地方因?yàn)?..
    飄蕩的小白閱讀 1,390評論 2 3
  • 《匆匆一聚》 久別重逢須百杯, 相見苦短難醉歡。 共赴機(jī)場又相送, 君飛虹橋我美蘭。 白云山人 20170927
    賽德傳播閱讀 574評論 0 0
  • 我喜歡過一個boy 那是在高二,我們是前后桌,我比較貪玩,叛逆。他是乖乖boy? no 乖戾 ( ?? .? ...
    風(fēng)格_168閱讀 475評論 0 0
  • 朋友圈中看到陸明光的《金澤少年的畫很有韻味》,轉(zhuǎn)發(fā)一篇文章,介紹金澤青少年畫的橋,畫得確實(shí)好。 有感而發(fā),寫了首小...
    黃葉村人閱讀 127評論 2 2