Handling window resize with arbitrary aspect ratios

Posted by DormoTheNord on Game Development See other posts from Game Development or by DormoTheNord
Published on 2012-10-20T01:25:56Z Indexed on 2012/10/20 5:22 UTC
Read the original article Hit count: 256

Filed under:
|
|

I'm currently making a 2D game using SFML. I want the aspect ratio to be maintained when the user resizes the window. I also want the game to work with any arbitrary aspect ratio (like any media player would).

Here is the code I have so far:

void os::GameEngine::setCameraViewport()
{
    sf::FloatRect tempViewport;

    float viewAspectRatio = (float)aspectRatio.x / aspectRatio.y;
    float screenAspectRatio = (float)gameWindow.getSize().x / gameWindow.getSize().y;

    if (viewAspectRatio > screenAspectRatio)
    {
        // Viewport is wider than screen, fit on X
    }
    else if (viewAspectRatio < screenAspectRatio)
    {
        // Screen is wider than viewport, fit on Y
    }
    else // window aspect ratio matches view aspect ratio
    {
        tempViewport.height = 1;
        tempViewport.width = 1;
        tempViewport.left = 0;
        tempViewport.top = 0;
    }

    viewport = tempViewport;

    camera.setViewport(viewport);

    gameWindow.setView(camera);
}

The problem is I'm having trouble with the logic to determine the properties of the viewport.

© Game Development or respective owner

Related posts about sfml

Related posts about resolution