Search code examples
iosswiftsprite-kitgame-physics

accelerometer data not correct, delayed for few seconds


I am creating a very simple game using Swift and SpriteKit and I am moving a ball on the screen using the accelerometer data (acceleration x,y).

I would say the code works fine but I have noticed that sometimes (often right when I open the app) the accelerometer data is not correct and delayed for few seconds.

Why is that happening?

I am using the following code to read the accelerometer data:

if motionManager.accelerometerAvailable == true {
        motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:{
            data, error in
            self.accX = CGFloat(data.acceleration.x)
            self.accY = CGFloat(data.acceleration.y)
        })
}

And the function update to apply some impulse to the ball:

override func update(currentTime: CFTimeInterval) {
    var impulse = CGVectorMake(accX, accY)
    var obj = childNodeWithName("ball") as SKSpriteNode
    obj.physicsBody?.applyImpulse(impulse)
}

Am i missing something?

Thank you


Solution

  • I have given priority to both functions and the issue seems fixed.

    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(dispatch_get_global_queue(priority, 0)) {
        // do some task
        dispatch_async(dispatch_get_main_queue()) {
            // code with priority
        }
    }