Monthly Archives: June 2014

Accelerometer, Sprite Kit, and Swift

So when iOS 7 was released I re-did my tutorial on using the Accelerometer with Sprite Kit instead of cocos2d. Now, in the fall, when iOS 8 is released there a whole new programming language for us to learn called “Swift“. There are plenty of articles out there about Swift, so I won’t go into it, i’ll stick to the programming and assume you know the basics. Apple released two iBooks on using Swift that are definitely recommended, “The Swift Programming Language” and “Using Swift with Cocoa and Objective-C

First, you have to make sure you have the latest Xcode 6 beta and running iOS 8 on one of your devices. I do not recommend using your everyday device for the betas since they are in fact betas. My iPad Air has beta 2 on it and the battery lasts 24 hrs and storage is always at 0, it made testing this code fun 🙂 Anyway, here is what I did. This may not be the best way to do this but it works.

Start Xcode 6 beta goto File > New > Project, make sure iOS > Application > Game is selected as your template. In GameScene.swift add this line import CoreMotion. You don’t need to #define things anymore, in Swift, you just use the let command so add these lines after your import:
let kPlayerSpeed = 250
let screenSize: CGRect = UIScreen.mainScreen().bounds

Delete everything after override func didMoveToView(view: SKView) { (make sure you keep the appropriate } though) and add the following to set up your sprite:
let monkey = SKSpriteNode(imageNamed:"monkey_arms_up")
monkey.position = CGPointMake(screenSize.width/2, screenSize.height/2)
self.addChild(monkey)

Pretty easy so far right? This last chunk of code was converted from my previous tutorial:
let motionManager: CMMotionManager = CMMotionManager()
if (motionManager.accelerometerAvailable) {
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue()) {
(data, error) in
let currentX = monkey.position.x
let currentY = monkey.position.y
if(data.acceleration.y < -0.25) { // tilting the device to the right var destX = (CGFloat(data.acceleration.y) * CGFloat(kPlayerSpeed) + CGFloat(currentX)) var destY = CGFloat(currentY) motionManager.accelerometerActive == true; let action = SKAction.moveTo(CGPointMake(destX, destY), duration: 1) monkey.runAction(action) } else if (data.acceleration.y > 0.25) { // tilting the device to the left
var destX = (CGFloat(data.acceleration.y) * CGFloat(kPlayerSpeed) + CGFloat(currentX))
var destY = CGFloat(currentY)
motionManager.accelerometerActive == true;
let action = SKAction.moveTo(CGPointMake(destX, destY), duration: 1)
monkey.runAction(action)
}
}

Build and run on your device and you should be set. Tilt your device to move the monkey left and right. Let me know via Twitter if this works for you! You can get all of the code on github.