C# Matrix4x4 multiplication problems with CreateRotationX / CreateRotateZ

Viewed 28

I have been using C#'s Matrix4x4 class, and I'm getting a bit confused.

In the public fields of the Matrix4x4 class, it clearly shows the definitions of all of its properties here:

#region Public Fields
        /// <summary>
        /// Value at row 1, column 1 of the matrix.
        /// </summary>
        public float M11;
        /// <summary>
        /// Value at row 1, column 2 of the matrix.
        /// </summary>
        public float M12;
        /// <summary>
        /// Value at row 1, column 3 of the matrix.
        /// </summary>
        public float M13;
        /// <summary>
        /// Value at row 1, column 4 of the matrix.
        /// </summary>
        public float M14;
 
        /// <summary>
        /// Value at row 2, column 1 of the matrix.
        /// </summary>
        public float M21;
        /// <summary>
        /// Value at row 2, column 2 of the matrix.
        /// </summary>
        public float M22;

But when examining it's CreateRotationX function:

        public static Matrix4x4 CreateRotationX(float radians)
        {
            Matrix4x4 result;
 
            float c = (float)Math.Cos(radians);
            float s = (float)Math.Sin(radians);
 
            // [  1  0  0  0 ]
            // [  0  c  s  0 ]
            // [  0 -s  c  0 ]
            // [  0  0  0  1 ]
            result.M11 = 1.0f;
            result.M12 = 0.0f;
            result.M13 = 0.0f;
            result.M14 = 0.0f;
            result.M21 = 0.0f;
            result.M22 = c;
            result.M23 = s;
            result.M24 = 0.0f;
            result.M31 = 0.0f;
            result.M32 = -s;
            result.M33 = c;
            result.M34 = 0.0f;
            result.M41 = 0.0f;
            result.M42 = 0.0f;
            result.M43 = 0.0f;
            result.M44 = 1.0f;
 
            return result;
        }

It transposes the values of result.M23 and result.M32.

enter image description here

Sure, the internal structure of how it represents it self can be in Row major or in Column major.

But then what I don't understand is when I do this:

   var matrix = CreateRotationZ(90 * 3.1415926535 / 180.0f) * CreateRotationX(94.84741 * 3.1415926535 / 180.0f)

The resulting multiplication gives me an incorrect answer:

0.0000 -0.0845 0.9964 0.0000
-1.0000 0.0000 0.0000 0.0000
0.0000 -0.9964 -0.0845 0.0000
0.0000 0.0000 0.0000 1.0000

with correct answer being (found by computing via Wolfram Alpha calculator):

  0.0000 0.0845 0.9964 0.0000
  1.0000 0.0000 0.0000 0.0000
  0.0000 0.9964 -0.0845 0.0000
  0.0000 0.0000 0.0000 1.0000

What's going on here? I'm sure it can't be a bug in C# Matrix4x4 and I am just perhaps using multiplication incorrectly?

0 Answers
Related