Search code examples
swiftarkitcore-motion

Calculating worldFront like in SCNARView


In SCNARView I can access a property of camera node called worldFront, which represents camera rotation. I would like to calculate similar vector from CoreMotion values not using SCNARView, just data from CoreMotion. So that I can get a vector that would be equal to worldFront in SCNARView if camera was facing the same direction. Can someone explain me how to calculate such a value?


Solution

  • I have found the answer:

    override var cameraFrontVector: double3 {
        guard let quaternion = motionService.deviceMotion?.attitude.quaternion else { return .zero }
    
        let x = 2 * -(quaternion.x * quaternion.z + quaternion.w * quaternion.y)
        let z = 2 *  (quaternion.y * quaternion.z - quaternion.w * quaternion.x)
        let y = 2 *  (quaternion.x * quaternion.x + quaternion.y * quaternion.y) - 1
    
        return double3(x: x, y: y, z: z)
    }
    

    This gives me values like worldFront in SCNNode.