Skip to content

Instantly share code, notes, and snippets.

@stanchiang
Forked from travisnewby/CMDeviceMotion.swift
Created August 30, 2016 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stanchiang/61c2f31e778fb6129dd5f2b0b1c772cf to your computer and use it in GitHub Desktop.
Save stanchiang/61c2f31e778fb6129dd5f2b0b1c772cf to your computer and use it in GitHub Desktop.
Determine the direction of "gaze" of the device in any orientation
extension CMDeviceMotion {
func gaze(atOrientation orientation: UIInterfaceOrientation) -> SCNVector4 {
let attitude = self.attitude.quaternion
let aq = GLKQuaternionMake(Float(attitude.x), Float(attitude.y), Float(attitude.z), Float(attitude.w))
let final: SCNVector4
switch UIApplication.sharedApplication().statusBarOrientation {
case .LandscapeRight:
let cq = GLKQuaternionMakeWithAngleAndAxis(Float(M_PI_2), 0, 1, 0)
let q = GLKQuaternionMultiply(cq, aq)
final = SCNVector4(x: -q.y, y: q.x, z: q.z, w: q.w)
case .LandscapeLeft:
let cq = GLKQuaternionMakeWithAngleAndAxis(Float(-M_PI_2), 0, 1, 0)
let q = GLKQuaternionMultiply(cq, aq)
final = SCNVector4(x: q.y, y: -q.x, z: q.z, w: q.w)
case .PortraitUpsideDown:
let cq = GLKQuaternionMakeWithAngleAndAxis(Float(M_PI_2), 1, 0, 0)
let q = GLKQuaternionMultiply(cq, aq)
final = SCNVector4(x: -q.x, y: -q.y, z: q.z, w: q.w)
case .Unknown:
fallthrough
case .Portrait:
let cq = GLKQuaternionMakeWithAngleAndAxis(Float(-M_PI_2), 1, 0, 0)
let q = GLKQuaternionMultiply(cq, aq)
final = SCNVector4(x: q.x, y: q.y, z: q.z, w: q.w)
}
return final
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment