accelerometer example code

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?

Accepted Reply

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

Replies

I would like to see some sample code (in Obj-C, not Swift) and more info in the docs as well.


-Brian

http://www.raywenderlich.com/forums/viewtopic.php?f=21&t=10339

This link has some info on using controllers.


Once you get a controller it looks something like:


-(void)evtControllerStateChanged {


NSArray *controllers = [GCController controllers];

if ([controllers count] > 0) {

GCController *controller = [controllers objectAtIndex:0];

controller.motion.valueChangedHandler = ^(GCMotion *motion) {


// Track motion of controller (remote) here.

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

Thanks!! This gives me a starting point to work with. I had problems with the axelSprite ( I was probuably missing something so I remmed it out). Most importantly I was able to see the accelerometer's X and Y values change as I moved the remote.