1
votes

I'm making a game in C# and XNA 4.0. It uses multiple objects (such as a player character, enemies, platforms, etc.), each with their own texture and hitbox. The objects are created and drawn using code similar to the following:

class Object
{
    Texture2D m_texture;
    Rectangle m_hitbox;

    public Object(Texture2D texture, Vector2 position)
    {
        m_texture = texture;
        m_hitbox = new Rectangle((int)position.X, (int)position.Y, texture.Width, texture.Height);
    }

    public void Draw(SpriteBatch spriteBatch)
    {
        spriteBatch.Draw(texture, m_hitbox, Color.White);
    }
}

Everything works properly, but I also want to allow the player to resize the game window. The main game class uses the following code to do so:

private void Update(GameTime gameTime)
{
    if (playerChangedWindowSize == true)
    {
        graphics.PreferredBackBufferHeight = newHeight;
        graphics.PreferredBackBufferWidth = newWidth;
        graphics.ApplyChanges();
    }
}

This will inevitably cause the positions and hitboxes of the objects to become inaccurate whenever the window size is changed. Is there an easy way for me to change the positions and hitboxes based on a new window size? If the new window width was twice as big as it was before I could probably just double the width of every object's hitbox, but I'm sure that's a terrible way of doing it.

1

1 Answers

1
votes

Consider normalizing your coordinate system to view space {0...1} and only apply the window dimensions scalar at the point of rendering.

View Space to Screen Space Conversion

Pseudo code for co-ordinates:

x' = x * screenResX
y' = y * screenResY

Similarly for dimensions. Let's say you have a 32x32 sprite originally designed for 1920x1080 and wish to scale so that it fits the same logical space on screen (so it doesn't appear unnaturally small):

r = 32 * screenResX' / screenResY
width' = width * r
height' = height * r

Then it won't matter what resolution the user has set.

If you are concerned over performance this may impose, then you can perform the above at screen resolution change time for a one-off computation. However you should still always keep the original viewspace {0...1}.

Collision Detection

It's arguably more efficient to perform CD on screen space coordinates

Hope this helps