一直好奇swift是如何实现物理碰撞的,最近参考了组里佬的demo,在此总结下UIDynamicAnimator笔记
几个专有名词:
1.UIDynamicAnimator (动画者)可以实现物理碰撞,重力动画,对象之间的交互等。将Behavior对象添加到Animator即可实现动力仿真。
2.UIDynamicItem 实现UIDynamicAnimator的对象(动力学元素),UIView都遵循UIDynamicItem协议,所以所有UIView都是UIDynamicItem。
3.UIDynamicBehavior (仿真行为),是动力学行为的父类,基本的动力学行为类UIGravityBehavior、UICollisionBehavior、UIAttachmentBehavior、UISnapBehavior、UIPushBehavior以及UIDynamicItemBehavior均继承自该父类。
如下图:
部分demo:
animator = UIDynamicAnimator(referenceView: backView)
gravity = UIGravityBehavior(items: dynamicItems)
//MARK: 重力矢量大小
gravity.magnitude = 0.8
//MARK: 设置边界
let collisionTop = UICollisionBehavior(items: dynamicItems)
let collisionLeft = UICollisionBehavior(items: dynamicItems)
let collisionRight = UICollisionBehavior(items: dynamicItems)
let collisionBottom = UICollisionBehavior(items: dynamicItems)
let pLeftTop = CGPoint(x: 0, y: 0)
let pRightTop = CGPoint(x: self.backView.frame.width, y: 0)
let pLeftBottom = CGPoint(x: 0, y: self.backView.frame.height-30)
let pRightBottom = CGPoint(x: self.backView.frame.width, y: self.backView.frame.height-30)
collisionTop.addBoundary(withIdentifier: "boundaryTop" as NSCopying, from: pLeftTop, to: pRightTop)
collisionLeft.addBoundary(withIdentifier: "boundaryLeft" as NSCopying, from: pLeftTop, to: pLeftBottom)
collisionRight.addBoundary(withIdentifier: "boundaryRight" as NSCopying, from: pRightBottom, to: pRightTop)
collisionBottom.addBoundary(withIdentifier: "boundaryBottom" as NSCopying, from: pLeftBottom, to: pRightBottom)
let beHavior = UIDynamicItemBehavior(items: dynamicItems)
beHavior.elasticity = 0.5
animator.addBehavior(gravity)
animator.addBehavior(collisionTop)
animator.addBehavior(collisionLeft)
animator.addBehavior(collisionRight)
animator.addBehavior(collisionBottom)
animator.addBehavior(beHavior)
详细知识学习:
[Swift] UIDynamicAnimator 介紹 | Sab.J 的碼農世界
参考:
Swift 动画相关 Animcation: UIDynamicAnimator_十月ooOO的博客-CSDN博客