Search code examples
iphoneopengl-esaccelerometerquaternions

iPhone GLGravity example using quaternions


GLGravity iPhone example showing how to use accelerometer and OpenGL suffers from Gimbal Lock problem. I'm wondering is there any code available using quaternion rotation instead of Euler angles? Any help will be greatly appreciated, I'm struggling with this from a long time without having a success ...


Solution

  • It helps to have a good grasp of the theory of things before trying to implement and use it oneself. Below are two introductory articles about using Quaternions for rotations. Both are primarily related to smooth rotation interpolations and avoiding gimbal lock in accumulated rotations:

    Gamedev.net - Quaternion Powers

    Gamasutra - Rotating Objects Using Quaternions

    Now as far as actual code goes, I would suggest getting, and using, an "industry strength" vector math library as opposed to rolling your own. My suggestion would be grabbing the LinearMath part of the Bullet Physics Middleware project. Bullet physics, and the included linear math library, is developed by some of Sony's top engineers and has been in active development for years. It's freely available, not restricted by any license (Zlib license), and is used by professional game developers all over the world. The lib is cross platform/architecture and compiles on anything from iPhone to PS3.

    The lib offers a Quaternion class that allows you to create quaternions from euler angles or from rotation about an arbitrary axis, e.g. using setEulerZYX. Once you have your quaternions, there are built in functions for all common operations applicable to them; plus, minus, mul, normalize, slerp and much more.

    For actually applying your final quaternion to OpenGL rendering, the Transform class allows you to construct a matrix from a quaternion. The transform class in turn includes a function getOpenGLMatrix that directly gives you a compatible matrix to pass to OpenGL.

    The lib also includes a host of other very useful matrix and vector classes and functions.

    Grab the latest Bullet dist from google code, or grab just the LinearMath portion of the code directly from subversion using: svn checkout http://bullet.googlecode.com/svn/trunk/src/LinearMath