Search Unity

Is it possible to get a Quaternion from a Matrix4x4?

Discussion in 'Scripting' started by scone, Jul 4, 2012.

  1. scone

    scone

    Joined:
    May 21, 2008
    Posts:
    244
    So... I'm trying to work with transformation matrices, and I'll admit that I lack real experience with them.

    I know that the matrix is the result of a couple of different sin/cos functions on the various euler angle values of the rotation, but is there a direct way to get the rotation component of the transform out of the 4x4 matrix? Are rotation and scale just not accessible once encoded in a transformation matrix?
     
  2. Diviner

    Diviner

    Joined:
    May 8, 2010
    Posts:
    677
    If you set up your Matrix properly then yes, it's not only possible, it's how Quaternions are generated. You do have to roll your own method to find it though, Unity doesn't just give it to you.

    A small correction, the matrix you're looking for isn't the result of euler calculations, it's the result of vector calculations.

    I could explain how this works in greater depth but I don't know exactly where you're stuck (at the matrix generation or at the Quaternion extraction from the final Matrix).
     
  3. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
  4. Diviner

    Diviner

    Joined:
    May 8, 2010
    Posts:
    677
    Alex, you can simplify your GetRotation method in that link using the functionality of Unity's API by doing :

    Code (csharp):
    1.  
    2. public static Quaternion GetRotation(this Matrix4x4 matrix)
    3.  
    4.     {
    5.  
    6.        return Quaternion.LookRotation(matrix.GetColumn(2), matrix.GetColumn(1));
    7.  
    8.     }
    9.  
    Keep it simple :)
     
    almaione-sdn likes this.
  5. alexzzzz

    alexzzzz

    Joined:
    Nov 20, 2010
    Posts:
    1,447
    That's cool!
     
  6. Guillaume-Swing

    Guillaume-Swing

    Joined:
    Nov 29, 2012
    Posts:
    5
    Will that work even if the matrix contains the scale?
     
  7. scone

    scone

    Joined:
    May 21, 2008
    Posts:
    244
    I ended up abandoning this line of reasoning because it ended up being a lossy process. I tried storing my TRS in a single 4x4 and when I made transformations to it, "unpacking" the TRS gave me a different result than a Unity Transform with the same transformations, leading me to believe that I "lost" information.