Skip to content

Instantly share code, notes, and snippets.

@garmstro
Created October 7, 2015 18:09
Show Gist options
  • Save garmstro/c1303d3c548284e7182c to your computer and use it in GitHub Desktop.
Save garmstro/c1303d3c548284e7182c to your computer and use it in GitHub Desktop.
/**
Calculates the pitch angle for the device based on it's orientation from the Quaternion
- parameter quat: The Quaternary from CMMotionManager.attitude
- returns: pitch The pitch of the device, scaled so that vertical is 0 degrees
*/
private func pitchFromQuaternion(quat: CMQuaternion) -> Double {
// http://stackoverflow.com/questions/9478630/get-pitch-yaw-roll-from-a-cmrotationmatrix/18764368#18764368
//let degRoll = radiansToDegrees(atan2(2*(quat.y*quat.w - quat.x*quat.z), 1 - 2*quat.y*quat.y - 2*quat.z*quat.z))
let degPitch = radiansToDegrees(atan2(2*(quat.x*quat.w + quat.y*quat.z), 1 - 2*quat.x*quat.x - 2*quat.z*quat.z))
let degYaw = radiansToDegrees(asin(2*quat.x*quat.y + 2*quat.w*quat.z))
var correctPitch = degPitch - 90.0 //Scale so that vertical is 0 (default is 90)
if orientation != nil {
switch orientation! {
case .Portrait:
break
case .PortraitUpsideDown:
correctPitch = -degPitch - 90.0
break
case .LandscapeLeft:
correctPitch = degYaw
break
case .LandscapeRight:
correctPitch = -degYaw
break
default:
break
}
}
return correctPitch
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment