重力行为 gravity
#import "DynamicView.h"
@interface DynamicView ()
// 仿真者
@property (strong, nonatomic) UIImageView *box;
// 仿真环境
@property (strong, nonatomic) UIDynamicAnimator *animator;
@end
@implementation DynamicView
- (instancetype)initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
_box = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Box"]];
_box.center = self.center;
[self addSubview:_box];
_animator = [[UIDynamicAnimator alloc]initWithReferenceView:self];
}
return self;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 创建物理行为并赋给执行者
UIGravityBehavior *gravity = [[UIGravityBehavior alloc]initWithItems:@[self.box]];
// 设置重力方向
gravity.gravityDirection = CGVectorMake(1, 0);
// 设置重力的角度(默认是90°)
gravity.angle = M_PI_2;
// 设置重力加速度
gravity.magnitude = 0.98;
// 将行为添加到仿真器
[self.animator addBehavior:gravity];
}
@end
吸附行为 snap
// 在执行捕捉之前,移除之前的行为
[self.animator removeAllBehaviors];
// 获取到触摸点
CGPoint location = [touches.anyObject locationInView:self];
// 创建捕捉行为
UISnapBehavior *snap = [[UISnapBehavior alloc]initWithItem:self.box snapToPoint:location];
//设置防震系数
//系数在(0~1之间,数值越大震动幅度越小)
snap.damping = arc4random_uniform(100)/99.0;
// 3.添加捕捉行为
[self.animator addBehavior:snap];
推动行为
刚性附加
弹性附加
碰撞检测