Swift/iOS: Moving objects with device motion (tilt screen)

One of the cool things of games on smartphones, is that you can control objects using the device motion. But how do you move an object using device tilt (using Swift 2)?

To do so you need to use the CMMotionManager (which is part of Apple’s CoreMotion framework). So don’t forget to include the framework at the top of your code: import CoreMotion.

You must also create one (single) CMMotionManager instance.

let motionManager: CMMotionManager = CMMotionManager()

And start the motion manager in the didMoveToView() function:

motionManager.startAccelerometerUpdates()

Once the motion manager is up and running, we can retrieve motion data from it using the accelerometerData member.

// Get node of object to move
let paddle = childNodeWithName(PaddleCategoryName) as! SKSpriteNode

// Get MotionManager data
if let data = motionManager.accelerometerData {
    
    // Only get use data if it is "tilt enough"
    if (fabs(data.acceleration.x) > 0.2) {
        
        // Apply force to the moving object
        paddle.physicsBody!.applyForce(CGVectorMake(40.0 * CGFloat(data.acceleration.x), 0))
        
    }
}

If you want to actually move the object, you need to make sure that the object has some physical properties:

// Rectangular physics body around the object
paddle.physicsBody = SKPhysicsBody(rectangleOfSize: paddle.frame.size)
 
// Make it dynamic
paddle.physicsBody!.dynamic = true
 
// We don't want the object to fall of the screen
paddle.physicsBody!.affectedByGravity = false
 
// Add some mass to it
paddle.physicsBody!.mass = 0.02

The data.acceleration member is a struct of type CMAcceleration which contains the acceleration along the x-, y- and z-axis.

struct CMAcceleration {
    var x: Double
    var y: Double
    var z: Double
}

The following image (source) explains the orientation of those axes.

CoreMotion CMAcceleration axes