Search code examples
c#matrixcameraxnatransformation

Order of Multiplication for Building Transformation matrix for 2D Camera in XNA/FNA


I was reading about 2D Camera in XNA and came across this function for creating the transformation matrix.

public Matrix get_transformation(GraphicsDevice graphicsDevice)
        {
            _transform =       // Thanks to o KB o for this solution
              Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
                                         Matrix.CreateRotationZ(Rotation) *
                                         Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                                         Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f, ViewportHeight * 0.5f, 0));
            return _transform;
        }

I can't seem to understand why the matrices are being multiplied left to right, when in actuality shouldn't they be multiplied from right to left ( right being the first transformation to be applied )?. I can't seem to get a grasp on how this is actually working. Any insight would be really helpful.

Thank you


Solution

  • XNA matrices are Row Major:

    https://learn.microsoft.com/en-us/previous-versions/windows/silverlight/dotnet-windows-silverlight/bb197911(v=xnagamestudio.35)

    Which means that the vectors are rows, not columns, and so multiplication order is from the left to the right. In your sample code the transforms will be applied in the following order: rotation first, then scaling and then translation. Take also into account that Row Major matrix is just the transpose of Column Major matrix, so all the math that you know from textbooks that usually use the Column Major convention can be used, you just need to transpose the matrices.