I'm trying to move a SKSpiteNode only on the x-axis using the device motion. Tilting the device to the left or right to move the sprite. I'm reading about CoreMotion but I have doubts on how to implement this in my game.Is CoreMotion the right tool for this? And which functions to use ? Thank you any help appreciated.
You should use CoreMotion framework. Here is how you can listen core motion updates.
1- Instantiate CMMotionManager
instance. This class is responsible to deliver motion events.
lazy var motionManager: CMMotionManager = {
let motion = CMMotionManager()
motion.accelerometerUpdateInterval = 1.0/10.0 // means update every 1 / 10 second
return motion
}()
2- Call startAccelerometerUpdates
method of motion manager. This will start your motion manager.
self.motionManager.startAccelerometerUpdates()
3- In the update
method of your SKScene
subclass you can read accelerometer values from motion manager. Here is how i used it.
let xForce = self.motionManager.accelerometerData.acceleration.x
self.playerNodeBody.velocity = CGVector(dx: xForce, dy: 0)