Move Sprites with Accelerometer in Sprite Kit with Swift

Most modern devices have an builtin accelerometer. In this tutorial we will move a sprite sideways according to the movement of the device. This tutorial is built with iOS 8.1 and Xcode 6.1

Open Xcode and choose iOS->Application->Game. 

or product name, use SpriteKitSwiftAccelerometerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

e need a sprite for this tutorial so download our image and add it to the project. Go to the GameScene.swift file. Here is the GameScene class defined. We need to read values from the accelerometer so we need to import the CoreMotion framework. Add the following line right after the import SpriteKit line

import CoreMotion

ext, add the following properties.

var airplane = SKSpriteNode()
var motionManager = CMMotionManager()
var destX:CGFloat  = 0.0

The CMMotionManager object is the gateway to the motion services provided by iOS. In the didMoveToView method the custom code is executed. . Delete the code after the "Setup your scene here" comment line and add the following lines

override func didMoveToView(view: SKView) {
    /* Setup your scene here */
    // 1
    airplane = SKSpriteNode(imageNamed: "Airplane")
    airplane.position = CGPointMake(frame.size.width/2, frame.size.height/2)
    if motionManager.accelerometerAvailable == true {
      // 2
      motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue(), withHandler:{
        data, error in
        var currentX = self.airplane.position.x
        // 3
        if data.acceleration.x < 0 {
          self.destX = currentX + CGFloat(data.acceleration.x * 100)
        else if data.acceleration.x > 0 {
          self.destX = currentX + CGFloat(data.acceleration.x * 100)
  1. he image is loaded and centered to the main view.
  2. The startAccelerometerUpdatesQueue method reads input from the accelerometer and constantly gets new updates.
  3. If the acceleration value is negative the  value be subtracted from the x position, so the airplane will move left. If the acceleration value is positive the value will be added to the x position.

The actual movement will be done on the update method, which will be called each frame.

override func update(currentTime: CFTimeInterval) {
    /* Called before each frame is rendered */
    var action = SKAction.moveToX(destX, duration: 1)

A moveToX action is assigned to the airplane. Build and Run this project on a device, since the Simulator doesn't have an accelerometer.

You can download the source code of the SpriteKitSwiftAccelerometerTutorial at the ioscreator repository on Github