UIDynamic--动力元素行为:UIDynamicItemBehavior

时间:2022-03-08 08:56:08

属性分析:

 @property (nonatomic, readonly, copy) NSArray* items;  

 @property (readwrite, nonatomic) CGFloat elasticity; // Usually between 0 (inelastic) and 1 (collide elastically) 弹性系数 在0~1之间
@property (readwrite, nonatomic) CGFloat friction; // 0 being no friction between objects slide along each other 摩擦力系数
@property (readwrite, nonatomic) CGFloat density; // 1 by default 跟size大小相关,计算物体块的质量。
@property (readwrite, nonatomic) CGFloat resistance; // 0: no velocity damping 阻力系数
@property (readwrite, nonatomic) CGFloat angularResistance; // 0: no angular velocity damping 旋转阻力
@property (readwrite, nonatomic) BOOL allowsRotation; // force an item to never rotate 是否能旋转

代码:

 //
// YFDynamicItemViewController.m
// BigShow1949
//
// Created by apple on 16/8/25.
// Copyright © 2016年 BigShowCompany. All rights reserved.
// #import "YFDynamicItemViewController.h" @interface YFDynamicItemViewController ()
@property(nonatomic,strong)UIDynamicAnimator *animator;
@property (nonatomic, strong) UIView *redView; @end @implementation YFDynamicItemViewController - (void)viewDidLoad { [super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor]; UIView *redView = [[UIView alloc] init];
redView.frame = CGRectMake(, , , );
redView.backgroundColor = [UIColor redColor];
self.redView = redView;
[self.view addSubview:redView];
} - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { [self testGravityAndCollsion];
}
/**
* 重力行为+碰撞检测
*/
-(void)testGravityAndCollsion
{
//1.重力行为
UIGravityBehavior *gravity=[[UIGravityBehavior alloc]init];
[gravity addItem:self.redView]; //2碰撞检测行为
UICollisionBehavior *collision=[[UICollisionBehavior alloc]init];
[collision addItem:self.redView];
//让参照视图的边框成为碰撞检测的边界
collision.translatesReferenceBoundsIntoBoundary=YES; // 动力元素行为
UIDynamicItemBehavior * itemBehavior = [[UIDynamicItemBehavior alloc] initWithItems:@[self.redView]];
itemBehavior.elasticity = 1.2;
itemBehavior.friction = .;
itemBehavior.density = ;
itemBehavior.resistance = ; // 阻力系数
itemBehavior.allowsRotation = NO;
itemBehavior.angularResistance = ; //3.执行仿真
[self.animator addBehavior:gravity];
[self.animator addBehavior:collision];
[self.animator addBehavior:itemBehavior];
} -(UIDynamicAnimator *)animator
{
if (_animator==nil) {
//创建物理仿真器(ReferenceView:参照视图,设置仿真范围)
self.animator=[[UIDynamicAnimator alloc]initWithReferenceView:self.view];
}
return _animator;
} @end