Search code examples
iossprite-kitgyroscopecore-motion

Teeter game using motion sensor


I'm relatively new to SpriteKit and I'm looking to make a game similar to Teeter so I can develop my personal knowledge. After spending a couple of days searching around the web I could not find any tutorials that teach you how to use iPhones motion sensors When the device is tilted) so I gave up and turned to Stack. More specific, I want to really know if there's away to maybe use CoreMotion framework together with SpriteKit as one. If not, what is "the best solution or approach" to developing a game such as Teeter that runs on iOS devices without using third party game engines?


Solution

  • Sure you can use Core Motion:

    @import CoreMotion;
    

    Here's an example implementation of accelerometer readings - declare an instance variable:

    CMMotionManager *_myMotionManager;
    

    Initial setup as you initialise your scene:

    _myMotionManager = [[CMMotionManager alloc] init];
    _myMotionManager.accelerometerUpdateInterval = 0.2; // tweak the sensitivity of intervals
    [_myMotionManager startAccelerometerUpdates];
    

    This is how to gather accelerometer data on the Y axis (there are three: X, Y, Z) - put this in the update method of your Sprite Kit game:

    float yAcceleration = _myMotionManager.accelerometerData.acceleration.y;
    NSLog(@"y axis acceleration data: %f", yAcceleration);
    


    Make sure you [_myMotionManager stopAccelerometerUpdates]; when they're no longer needed.

    If you need gyroscope data, the approach is very similar - here, you'd start gyro updates and use _myMotionManager.gyroData.rotationRate.y instead.