Well, if you want to use it for 2D games (assuming from the tags), you only need a Transform
matrix to apply to the SpriteBatch
, you don't need World
and Projection
matrices.
So, when you're drawing an object that should be drawn inside your game world (e.g. the main player), you use the following Begin
method from SpriteBatch
(XNA 4.0, replace the other parameters by what you need):
spriteBatch.Begin(SpriteSortMode.Immediate, null, null, null, null, effect, camera.Transform);
/*
Draw the world objects like walls, players, weapons, etc.
...
*/
spriteBatch.End();
This will apply the camera's effect to the drawing, simulating a camera within your world.
For other visual elements that are not part of the world (like the HUD with player health, etc.), you just use the regular Begin
method (without the camera's matrix as a parameter) to draw it, because you don't really want them to move all around the screen when the camera moves, you want them to be static.
The way the camera works is that it applies a translation matrix going in the opposite direction of where you want your camera to be (it explains the negative signs in Matrix.CreateTranslation(-Position.X, -Position.Y, 0)
to simulate a camera moving inside a world. In fact, what you're really doing is that you're moving the world around so that the camera's view is represented by the game's window.
So, say you want your camera to move to the right by 20 pixels, you want to move your whole world to the left by 20 pixels to give the user the feeling that they moved to the right. This is achieved by applying the camera's matrix to all the world objects, to sort of move them around.
The same goes for scaling and rotation, you move the world around when you're drawing them to give a feeling
of change.