UIDynamic
物理引擎UIDynamic是IOS7引入的一項(xiàng)新技術(shù)。他包括
UIGravityBehavior:重力行為
UICollisionBehavior:碰撞行為
UISnapBehavior:捕捉行為
UIPushBehavior:推動(dòng)行為
UIAttachmentBehavior:附著行為
UIDynamicItemBehavior:動(dòng)力元素行為
有些時(shí)候會(huì)運(yùn)用到一些簡(jiǎn)單動(dòng)畫上面,也可以寫一點(diǎn)好玩的小demo,比如下圖。(重力、碰撞)或者多種相結(jié)合,也可以完成一些很復(fù)雜的動(dòng)畫。

看不見我看不見我.gif
下面,樓主就來簡(jiǎn)單介紹下這個(gè)demo的實(shí)現(xiàn),用到的效果只有重力和碰撞效果。
首先創(chuàng)建物理仿真器、重力對(duì)象屬性、碰撞屬性。
@property(nonatomic,strong)UIDynamicAnimator *animator;
@property(nonatomic,strong)UIGravityBehavior *gravity;
@property(nonatomic,strong)UICollisionBehavior *collision;
然后懶加載物理仿真器、重力對(duì)象和碰撞對(duì)象
-(UIDynamicAnimator *)animator{
if (!_animator) {
//參數(shù):指定那個(gè)范圍內(nèi)有物理特性
_animator = [[UIDynamicAnimator alloc]initWithReferenceView:self.view];
}
return _animator;
}
-(UIGravityBehavior *)gravity{
if (!_gravity) {
//參數(shù):一般是一些控件,指定那些東西有重力特性,(這里由于我們是直接給view加重力效果,下面會(huì)講到,所以這里不用設(shè)置)
_gravity = [[UIGravityBehavior alloc]initWithItems:@[]];
/*****設(shè)置重力加速度 與方向
dx = 0 dy > 0 重力正下
dx = 0 dy < 0 重力正上
dx < 0 dy = 0 重力往左
dx > 0 dy = 0 重力往右
1為一倍重力加速度
_gravity.gravityDirection = CGVectorMake(dx, dy);
*****/
_gravity.gravityDirection = CGVectorMake(1, -1);
//將重力特性添加到物理仿真器上面
[self.animator addBehavior:_gravity];
}
return _gravity;
}
-(UICollisionBehavior *)collision{
if (!_collision) {
//參數(shù):一般是一些控件,指定那些東西有重力特性
_collision = [[UICollisionBehavior alloc]initWithItems:@[]];
//設(shè)置碰撞邊界
_collision.translatesReferenceBoundsIntoBoundary = YES;
[self.animator addBehavior:_collision];
}
return _collision;
}
為了方便,我是點(diǎn)擊屏幕創(chuàng)建一個(gè)view,所以重寫它的TouchBegan或者TouchEnd方法都行。這個(gè)隨意,只要有個(gè)交互事件就行了。
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch *touch = [touches anyObject];
CGPoint point = [touch locationInView:self.view];
UIView *view = [[UIView alloc]initWithFrame:CGRectMake(point.x-15, point.y-15, 30, 30)];
view.backgroundColor = [UIColor colorWithRed:arc4random()%256/255.0 green:arc4random()%256/255.0 blue:arc4random()%256/255.0 alpha:1];
[self.view addSubview:view];
//添加重力、碰撞的對(duì)象
[self.gravity addItem:view];
[self.collision addItem:view];
}
這樣我們就給view添加了重力和碰撞了。如果想實(shí)現(xiàn)樓主那種“亂飛”的感覺,只需要添加一個(gè)timer,每過一秒改變一下重力的方向就行了。