I'm trying to use the accelerometer in my game. The GCMotion reference doc gives some information, but I still don't know where to begin to add accelerometer funtionality to my game. Are there any example's that show how to use the accelerometer?
I have been scratching my head a bit regarding this too. This is how far I came trying to solve the problem in the most simple way.
In the app-delegate I added this:
var motionDelegate: ReactToMotionEvents? = nil
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let center = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "setupControllers:", name: GCControllerDidConnectNotification, object: nil)
center.addObserver(self, selector: "setupControllers:", name: GCControllerDidDisconnectNotification, object: nil)
GCController.startWirelessControllerDiscoveryWithCompletionHandler { () -> Void in
}
return true
}
func setupControllers(notif: NSNotification) {
print("controller connection")
let controllers = GCController.controllers()
for controller in controllers {
controller.motion?.valueChangedHandler = { (motion: GCMotion)->() in
if let delegate = self.motionDelegate {
delegate.motionUpdate(motion)
}
}
}
}
protocol ReactToMotionEvents {
func motionUpdate(motion: GCMotion) -> Void
}
Here is my GameScene.swift
import SpriteKit
import GameController
class GameScene: SKScene, ReactToMotionEvents {
var axelSprite: SKNode? = nil
var dest: CGPoint = CGPointMake(500, 500)
override func didMoveToView(view: SKView) {
/
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
appDelegate.motionDelegate = self
axelSprite = self.childNodeWithName("AxelSprite")
}
override func update(currentTime: CFTimeInterval) {
/ Called before each frame is rendered */
let action = SKAction.moveTo(self.dest, duration: 0.1)
self.axelSprite!.runAction(action)
}
func motionUpdate(motion: GCMotion) {
let current = self.axelSprite!.position
self.dest = CGPoint(x: current.x + CGFloat(motion.userAcceleration.x * 50), y: current.y + CGFloat(motion.userAcceleration.y * 50))
print("x: \(motion.userAcceleration.x) y: \(motion.userAcceleration.y)")
}
}
It's working but I feel that I'm shooting from the hip here and I'm a bit concerned that all is done on the main thread. I'm not satisfied by the way it moves the sprite, but it's a start... :-) I'd love to get comments on improvements...
/johan