Search code examples
swiftmatrixaugmented-realityscenekitarkit

ARKit – eulerAngles of Transform Matrix 4x4


In my project I have a transform and I want to get the orientation of that transform in eulersAngles.

How do I get the eulerAngles from a transform of 4x4 matrix in Swift language?

I need at least the Pitch, I may need the Yaw and I might need the Roll.


Solution

  • Assuming mij is matrix element in the i-th row and j-th column.

    R=atan2(m12, m22)
    c2 = sqrt(m00^2 + m01^2)
    P = atan2(-m02, c2)
    s1 = sin(R), c1 = cos(R)
    Y = atan2(s1*m20 - c1*m10, c1*m11-s1*m21)
    

    Source: The math is described in this document really well: https://pdfs.semanticscholar.org/6681/37fa4b875d890f446e689eea1e334bcf6bf6.pdf

    As opposed to going to quaternion, there are some corner cases (gimbal lock) you have to worry about that the above solution handles pretty well.