How do I apply multiple matrices in spriteBatch.Draw()?

256 views Asked by At

I'm making a game in C# and XNA 4.0. In some levels I need a camera matrix to make the level appear to scroll left/right. Additionally, I also need a scaling matrix to scale the graphics when the settings are used to change the window size. Both of my matrices are functional, but I'm currently calling them in the draw method like this:

if (scrollingLevel)
{
    //Use the camera matrix to make the stage scroll
    spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, camera.transform);
}
else
{
    //Use the scaling matrix to scale the graphics
    spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, null, transform);
}

What I want is to apply both matrices at the same time if it is a scrolling level (scale the graphics based on the window size and then use the camera matrix to make the level scroll). However, simply adding and multiplying the matrices does not produce an accurate result (adding prevents the graphics from scaling to the exact amount that they should and multiplying makes the camera scroll inaccurately). How can I apply both of the matrices at once?

1

There are 1 answers

0
Jaanus Varus On BEST ANSWER

Simply multiply the matrices before passing to spriteBatch.Begin.

Matrix multiplication allows the effects of both matrices appended into a single matrix. Note that this operation is not commutative, meaning that A * B != B * A.

In your case, you should probably multiply scaling matrix with the camera matrix.