Tap Swipe Pinch |
A blog about iPhone dev |
The gyroscope in the iPhone 4 and the new iPod Touch are great sensors for accurately detecting the device’s motion. When combined with the accelerometer data, the Core Motion framework can return a measurement called ‘Attitude’ which is a set of numbers that describe how the device has moved from a frame of reference. Attitude can be difficult to accurately explain in text, but completing this tutorial will give you an app that displays the Attitude measurements as the device moves making it easy to visualize and understand.
The first thing you need to do to get started with Core Motion is add the Core Motion framework into your project and include it in HelloWorldLayer.h

Next, we’ll add variables for both a label (which we’ll update with the Core Motion data points) and a reference to a CMMotionManager object. The CMMotionManager is what allows us to access the motion data points.

You initialize the CMMotionManager and the label in your HelloWorldLayer’s init method:

We set the deviceMotionUpdateInterval to our ideal refresh rate (60 Hz) since we’ll be pulling in motion data at every frame. Then we check to make sure motion data is available (it won’t be on devices without a gyroscope) and we start the updates.
We can now access the latest motion data in our update method by accessing the motionManager’s deviceMotion property. There’s a lot of data encompassed in the CMDeviceMotion object we get back including rotation rate and the direction of gravity, but we’ll look at the Attitude property and it’s three measurements so we can see how the device has rotated along it’s three axes. We’ll then rotate the the label with the yaw so that it’s always in the same orientation as the device is rotated around:

Since Cocos2D accepts rotation in degrees, we convert the yaw measurement using CC_RADIANS_TO_DEGREES. Also, note that the CMAttitude is the change in device rotation from a frame of reference. That frame of reference is the orientation of the device when we called [motionManager startDeviceMotionUpdates]. We can alter the frame of reference by multiplying the current attitude by the inverse of the attitude which we want to use as the frame of reference. Let’s assume we want to change the frame of reference whenever the user touches the screen. I will add [self registerWithTouchDispatcher]; to the HelloWorldLayer’s init method, and also add a referenceFrame CMAttitude variable to the header file. Then we can add the code below to handle touches which will store a frame of reference:

To display the roll, pitch, and yaw according to the new reference frame, we add a couple lines of code to check for a referenceFrame and then multiply by it’s inverse:

Now, when you tap the screen, you will be effectively resetting the reference frame which moves the label back to it’s original position and changes roll, pitch, and yaw to zero.