I am trying to add gravity to a group of buttons so they move around the screen when the device is tilted. The objects move and so long as the device is always in motion they keep moving, but once the device is still for at least 1 second, they stop moving completely, and stick to the edge even if I move the device after that.
Here is my code:
In the ViewController.Swift
var animator: UIDynamicAnimator!
var gravity: UIGravityBehavior!
var collision: UICollisionBehavior!
var motionManager = CMMotionManager()
var motionQueue = NSOperationQueue()
let itemBehavior = UIDynamicItemBehavior()
These two are called int he ViewDidLoad()
func addBehaviours (){
animator = UIDynamicAnimator(referenceView: view)
gravity = UIGravityBehavior(items: [emailButton,facebookButton])
animator.addBehavior(gravity)
itemBehavior.friction = 0.1;
itemBehavior.elasticity = 0.5
animator?.addBehavior(itemBehavior)
collision = UICollisionBehavior(items: [emailButton, facebookButton])
collision.translatesReferenceBoundsIntoBoundary = true
animator.addBehavior(collision)
itemBehavior.addItem(emailButton)
itemBehavior.addItem(facebookButton)
}
func updateMotion () {
motionManager.startDeviceMotionUpdatesToQueue(motionQueue) { (motion: CMDeviceMotion?, error: NSError?) -> Void in
self.gravity.gravityDirection = CGVectorMake(CGFloat((motion?.gravity.x)!), -CGFloat((motion?.gravity.y)!))
}
}