Search code examples
iossprite-kitcore-motion

Rotating a SpriteKit sprite’s z rotation with gyroscope data


I have the setup for core motion implemented, but can’t figure out how to keep the rotation of my sprite so it follows the rotation of the iPhone (on the z axis).

updates code:

[self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
                                            withHandler:^(CMDeviceMotion *motion, NSError *error)
{
    mySprite.zRotation = ?;
}];

Any ideas?


Solution

  • CMAttitude is the class you're looking for. When you're update block fires, you access the devices attitude though the attitude property on the CMDeviceMotion instance. From attitude, you can directly ask the device for all kinds of interesting info about its rotation, but for your use case, you probably only need to ask for yaw.

    And assuming of course that you don't need these values transformed in any way, you can pump them straight into the sprite's zRotation, and you should receive the expected results.

    [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
                                            withHandler:^(CMDeviceMotion *motion, NSError *error) {
                                                mySprite.zRotation = motion.attitude.yaw;
                                            }];
    

    enter image description here Image from http://uqtimes.blogspot.com/2012/05/3-coremotion.html