How to make this floating views animation in swift uikit with uiviews
- each views doesn't collapse each other.
- each view position is random to 16 px and slow moving.
I have tried with this code and calling push function several times
import UIKit
lazy var collision: UICollisionBehavior = {
let collision = UICollisionBehavior()
collision.translatesReferenceBoundsIntoBoundary = true
collision.collisionDelegate = self
collision.collisionMode = .everything
return collision
}()
lazy var itemBehaviour: UIDynamicItemBehavior = {
let behaviou = UIDynamicItemBehavior()
behaviou.allowsRotation = false
return behaviou
}()
func addingPushBehaviour(onView view: UIDynamicItem ,animationAdded: Bool = false) {
let push = UIPushBehavior(items: [view], mode: .instantaneous)
push.angle = CGFloat(arc4random())
push.magnitude = 0.005
push.action = { [weak self] in
self?.removeChildBehavior(push)
}
addChildBehavior(push)
}
func addItem(withItem item: UIDynamicItem) {
collision.addItem(item)
itemBehaviour.addItem(item)
addingPushBehaviour(onView: item)
}
override init() {
super.init()
addChildBehavior(collision)
addChildBehavior(itemBehaviour)
}
var mainView: UIView?
convenience init(animator: UIDynamicAnimator , onView: UIView) {
self.init()
self.mainView = onView
animator.addBehavior(self)
}
Correct me if I'm wrong, but it sounds like there are two tasks here: 1) randomly populate the screen with non-overlapping balls, and 2) let those balls float around such that they bounce off each other on collision.
If the problem is that the animations are jerky, then why not abandon
UIDynamicAnimatorand write the physics from scratch? Fiddling with janky features in Apple's libraries can waste countless hours, so just take the sure-fire route. The math is simple enough, plus you can have direct control over frame rate.Keep a list of the balls and their velocities:
When creating a ball, randomly generate a position that does not overlap with any other ball:
Then run a
whileloop on a background thread that updates the positions however often you want:Here are the helper functions:
Result
https://i.stack.imgur.com/npMGp.jpg
Let me know if anything goes wrong, I'm more than happy to help.