Handling window resize with arbitrary aspect ratios
- by DormoTheNord
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.