一,重力行爲
// 1.創建物理仿真器
// 並且指定了當前控制器的view作爲仿真範圍
// UIDynamicAnimator *anim = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
// 2.創建物理仿真行爲
注:以上代碼需要寫成全局變量,如下:
- (UIDynamicAnimator *)anim{
if (!_anim) {
_anim = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
}
return _anim;
}
// 並且指定紅色爲作爲仿真元素
UIGravityBehavior *gravityB = [[UIGravityBehavior alloc] initWithItems:@[self.redView]];
// 設置重力的方向
// gravityB.gravityDirection = CGVectorMake(1, 0);
// gravityB.gravityDirection = CGVectorMake(0, -1);
// gravityB.gravityDirection = CGVectorMake(1, 1);
// 設置重力的角度
// gravityB.angle = M_PI_2;
// 設置重力的加速度
gravityB.magnitude = 100.0;
// 3.將物理仿真行爲添加到仿真器中
[self.anim addBehavior:gravityB];
}
二,碰撞
// 碰撞
// 1.創建物理仿真器
// 2.創建物理仿真行爲
UIGravityBehavior *gravigtyB = [[UIGravityBehavior alloc] initWithItems:@[self.redView]];
// gravigtyB.magnitude = 100;
// 創建碰撞仿真行爲
UICollisionBehavior *collisionB = [[UICollisionBehavior alloc] initWithItems:@[self.redView, self.st]];
// 設置碰撞的邊界
// collisionB.translatesReferenceBoundsIntoBoundary = YES;
// 添加直線邊界
// [collisionB addBoundaryWithIdentifier:@"line" fromPoint:CGPointMake(0, 200) toPoint:CGPointMake(320, 420)];
// 添加圖形的邊界
UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:self.view.frame];
[collisionB addBoundaryWithIdentifier:@"abc" forPath:path];
// 3.將物理仿真行爲添加到仿真器中
[self.anim addBehavior:gravigtyB];
[self.anim addBehavior:collisionB];
}
三,吸附行爲
// 1.獲取當前觸摸的手指
UITouch *touch = [touches anyObject];
// 2.更具手指取出位置
CGPoint point = [touch locationInView:touch.view];
// 吸附行爲
// 1.創建物理仿真器
// 2.創建物理仿真行爲
UISnapBehavior *snapB = [[UISnapBehavior alloc] initWithItem:self.redView snapToPoint:point];
// 設置吸附行爲的"減震"
snapB.damping = 0;
// 注意: 吸附行爲默認只能吸附一次, 如果多次吸附必須從仿真器中移除再重新添加
[self.anim removeAllBehaviors];
// 3.將物理仿真行爲添加到仿真器中
[self.anim addBehavior:snapB];
}