GLKit – Transforming A Vector With A Quaternion

OpenGL 3d axes

Since I haven’t seen this on Stackoverflow, the following is a method to transform a vector (GLKVector3) based on an attitude quaternion (GLKQuaternion).

First, assume that you have a GLKVector3 as input, call it inputVector3. inputVector3 could be yaw, pitch, and roll influences from an aircraft’s control surfaces or thruster output on a spacecraft. You know your vehicle’s attitude and have calculated that attitude into a quaternion. So, the goal is to have the inputVector3 transformed into an ivar, say GLKVector3 deltaV, that is in terms of the vehicle’s attitude.

- (GLKVector3)transformVector3:(GLKVector3)inputVector3 withAttitudeQuaternion:(GLKQuaternion)attitudeQuaternion
GLKVector3 deltaV = inputVector3;

//Always ensure that your attitude quaternion has been normalized
attitudeQuaternion = GLKQuaternionNormalize(attitudeQuaternion);

//Convert the normalized attitude quaternion into a GLKMatrix3.
GLKMatrix3 tempQMatrix3 = GLKMatrix3MakeWithQuaternion(attitudeQuaternion);

//Since v' = v T, where T is a transform matrix, multiply
//the attitudeQuaternion GLKMatrix3 with the necessary GLKVector3.
deltaV = GLKMatrix3MultiplyVector3(tempQM3, deltaV);

return deltaV;