1
votes

I´m new to XNA and playing around with the spritebatch. There is a problem I can't fix inside of my head.

I have a Class called Sprite. This sprite got a Vector2 which stores the position of the sprite inside of the screen. I draw the sprite using Spritebatch with a call like this:

spriteBatch.Draw(this.texture, this.position, Color.White);

Imagine I design a scene or screen with this type of coordinates. Maybe there is a floor that should be at the bottom of my scene. When I place it at a fix position and someone plays it at a larger resolution the floor would not be at the bottom of my scene.

Is there a way to work inside of a defined space that is independent of the ViewPort Width and Height?

I have read several articles here. Is the only solution to render to a RenderTarget first and then scale this and render it to the viewport?

I hope you can help me and protect me from getting crazy :) !

Thanks.

1

1 Answers

0
votes

There is no predefined way to stretch a viewport to fit neatly onto the screen and have all your sprites looking like their in order. Rendering to a render target is a good way to scale though may be a bit difficult. Especially if you get into post processing effects.

To scale your game there is a few things that we need to do. First you need to choose a default resolution such as 800x600. Get your game fully fleshed out and working in a resolution such as this.

Once you have the game ready in this resolution we can change the screen size and still fit everything nicely.

First get the width and the height of the viewport

float width = GraphicsDevice.Viewport.Width;
float height = GraphicsDevice.Viewport.Height;

Now find the scale multiplier:

float xScale = width / 800.0f;
float yScale = height / 600.0f;

The scale values must be a float or double and it is imperative that your constants from your default resolution also be floats or doubles. If their not then the decimal places will be omitted when we perform the calculations. Leaving us with a rounded whole number which is not accurate and will cause improper scaling.

Now that we have the scale we can make some modifications simply by multiplying our scale factors by our position and size values.

Lets say your sprite position was

pos.x = 400;
pos.y = 240;

it would now become

pos.x = 400 * xScale;
pos.y = 240 * yScale;

Now this means that we change how you draw the sprite a little bit

spritebatch.Draw(this.texture, new Rectangle(this.position.x, this.position.y, this.texture.Width * xScale, this.texture.Height * yScale), Color.white);

Here we are drawing the sprite at its scaled position and scaling its size based on the size of the texture we are trying to draw.

Note: when you scale using this method all of your sizes and position for collision as well will need to be scaled in order for this to work.