Skip to content

Instantly share code, notes, and snippets.

@travisnewby
Last active November 12, 2022 17:13
Show Gist options
  • Save travisnewby/96ee1ac2bc2002f1d480 to your computer and use it in GitHub Desktop.
Save travisnewby/96ee1ac2bc2002f1d480 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 orientation {
case .landscapeRight:
let cq = GLKQuaternionMakeWithAngleAndAxis(Float.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.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.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:
fallthrough
@unknown default:
let cq = GLKQuaternionMakeWithAngleAndAxis(-Float.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
}
}
@ostholz
Copy link

ostholz commented Sep 16, 2019

thank you for your "magic" extension.

@travisnewby
Copy link
Author

@ostholz you’re welcome.

@tfalves
Copy link

tfalves commented Jul 19, 2020

Thank you very much for this! Saves a lot of headaches!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment