Move Sprites with Accelerometer iOS Tutorial

All modern iOS devices have an built-in accelerometer. In this tutorial a sprite will move sideways according to the movement of the device. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Game.

For product name, use IOSMoveSpritesAccelerometerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the GameScene.sks file and delete the hello World label. Select the Scene and in the Attributes inspector change the X and Y values of the Anchor point to 0.

A sprite is needed for this tutorial so download our image and drag it to the Assets folder inside the project. The Game template added some code to the project we will not need. Go to the GameScene.swift file and delete all code inside the GameScene class. To read values from the accelerometer the CoreMotion framework needs to be imported. Add the following line right after the import SpriteKit line

import CoreMotion

Next, 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.

override func didMove(to view: SKView) {
       
    // 1      
    airplane = SKSpriteNode(imageNamed: "Airplane")
    airplane.position = CGPoint(x: frame.size.width/2, y: frame.size.height/2)
    self.addChild(airplane)

    if motionManager.isAccelerometerAvailable {
        // 2
        motionManager.accelerometerUpdateInterval = 0.01
        motionManager.startAccelerometerUpdates(to: .main) {
            (data, error) in
            guard let data = data, error == nil else {
                return
            }

            // 3
            let currentX = self.airplane.position.x
            self.destX = currentX + CGFloat(data.acceleration.x * 500)
        }
    }
}
  1. The image is loaded and centered to the main view.

  2. The startAccelerometerUpdates(to:withHandler:) method reads input from the accelerometer and constantly gets new updates.

  3. The x position of the image will be updated by adding the current value of the accelerometer

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

override func update(_ currentTime: TimeInterval) {
    let action = SKAction.moveTo(x: destX, duration: 1)
    airplane.run(action)
}

A moveTo 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 IOSMoveSpritesAccelerometerTutorial at the ioscreator repository on Github