0
votes

I am making a game using sprite-kit. In my game I am using the accelerometer to move the node side to side by tilting the device. The following code works smoothly but after 8-10 game restarts, it kind of lags a bit to respond to the tilt. I then close the application and the problem repeats it self.

I have motionManger.startAccelerometerUpdates() in didMove(to view: SKView) and have a function that looks like so

    func processUserMotion(forUpdate currentTime: CFTimeInterval) {



    Ball.position.x += xAcceleration * 50 // xAcceleration is a variable that is a CGFloat = 0

    motionManger.accelerometerUpdateInterval = 0.1
    motionManger.startAccelerometerUpdates(to: OperationQueue.current!) { (data:CMAccelerometerData?, error:Error?) in
        if let accelerometerData = data {
            let acceleration = accelerometerData.acceleration
            self.xAcceleration = CGFloat(acceleration.x) * 0.75 + self.xAcceleration * 0.25
        }
    }


}

 override func update(_ currentTime: TimeInterval) {

     processUserMotion(forUpdate: currentTime)
 }

Any idea why this is happening or a better way to make the node respond well when the device is being tilted to left and right? Thanks!

UPDATE:

I finally figured out why the accelorometer was lagging. All I had to do was add motionManger.stopAccelerometerUpdates() to my GameOver scene. After doing so, I would transition back to GameScene 30 plus times and it responds well! Hope this little error helps someone in the future!

1
Did you check if the scene is being deallocated? If not, add deinit{print"deinit"} to your scene class and transition to a new scene.0x141E
Yes I did check and it is being deallocated. I found my solution. Rookie mistake! In my gameover function, I forgot to add motionManger.stopAccelerometerUpdates().sicvayne

1 Answers

0
votes

CMMotionManager.startAccelerometerUpdates must be used as a reference to one of your variables, it is not necessary to run it every time you generate a movement.

For example in Swift 3

class GameScene: SKScene {

    private var ballNode : SKSpriteNode?
    private let manager = CMMotionManager()

    override func didMove(to view: SKView) {

        self.ballNode = self.childNode(withName: "ball") as? SKSpriteNode

        manager.startAccelerometerUpdates()
        manager.accelerometerUpdateInterval = 0.01
        manager.startAccelerometerUpdates(to: OperationQueue.current!){ (data:CMAccelerometerData?, error:Error?) in
            if let accelerometerData = data {
                let acceleration = accelerometerData.acceleration
                self.ballNode?.physicsBody?.velocity.dx += 10*CGFloat(acceleration.x)
            }
        }


    }
    override func update(_ currentTime: TimeInterval) {
        //nothing here
    }
}

Source code: https://github.com/Maetschl/SpriteKitExamples/tree/master/CoreMotionTest