简体   繁体   中英

Objects stop moving - UIDynamics and Swift iOS

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)!))


    }

}

First, reduce the rate of updates by setting the motion manager's deviceMotionUpdateInterval to something like 0.2 (ie, much less often than the animator's frame rate). Then, change this line:

motionManager.startDeviceMotionUpdatesToQueue(motionQueue) { // ...

to this:

motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.mainQueue()) { // ...

Everything you are planning to do in your handler involves talking to the animator or its allies (ie the gravity behavior), and that needs to be done on the main thread. So there is no point receiving your updates on a background queue, as you are doing now, because you need to get onto the main thread immediately anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM