Tuesday, April 19, 2016

xna - How can I use a camera matrix with different resolutions?



I created a little jump'n'run game. The character(Mario) is always the center of the viewport. The game is running correctly if I use the resolution 800x480 pixel. But when I use another resolution(for example 1280x768), the sprites in the viewport look completely different to the sprites in the 800x480 viewport. I want that the viewport(and the sprites in the viewport) looks always the same, on every single resolution.


How can I do that? Should I change something on my camera matrix parameters or what should I change so that the viewport and the proportions of the sprites look always the same?


I use Monogame to run the game on different Windows Phone devices.


My camera class:


 public class Camera 
{
public Vector2 Cameraposition;

public Camera(Vector2 cameraposition)
{

Cameraposition = cameraposition;
}

public void Update(GameTime gameTime, Vector2 CamPosition)
{
Cameraposition = CamPosition;
}

public Matrix GetMatrix()
{

return new Matrix(1, 0, 0, 0, 0, 1, 0, 0, Cameraposition.X, Cameraposition.Y, 1, 0, -Cameraposition.X, -Cameraposition.Y, 0, 1);
}
}

In Game1:


//I use the camera in Game1 like this:
//At the beginning(in LoadContent):
Vector2 cameraposition = new Vector2(PlayerStartpos.X - GraphicsDevice.Viewport.Width / 2, PlayerStartpos.Y - GraphicsDevice.Viewport.Height / 2);
camera = new Camera(cameraposition);


//Updating the camera position
protected override void Update(GameTime gameTime)
{
player.Update(gameTime);
Newcameraposition = new Vector2(player.Playerposition.X - GraphicsDevice.Viewport.Width / 2, player.Playerposition.Y - GraphicsDevice.Viewport.Height / 2);
camera.Update(gameTime, Newcameraposition);

base.Update(gameTime);
}


//Drawing:
spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, SamplerState.AnisotropicClamp, DepthStencilState.None, RasterizerState.CullNone, null, camera.GetMatrix());
...

Answer



Your question is not an exact duplicate, so I won't try to close it. But it's close enough that I feel comfortable in simply sending you over to my old answer on Supporting Multiple Resolutions.


That answer is specifically for the XNA Platformer Sample, so you should probably download a copy of that to play around with to get a feel for how the code in my answer works. Then you can apply it to your own game.




Note, in particular, how I use matrix multiplication to combine two matrix operations, as mentioned in comments on your question:


Matrix camera = Matrix.CreateScale(scale, scale, 1)
* Matrix.CreateTranslation(translateX, translateY, 0);

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...