Whenever you work on 2D games, one of the most common concerns is whether your GUI will look good on every screen resolution, or if things are going to be in the place you expect them to be.

Another issue that pops into mind, is fairness. As some devices have more screen space, meaning more playing area, this would signify an advantage over other players. Obviously this depends entirely on the type of game you are developing as it can just mean more dead space.

If you are working on a platform that scales things automatically, maybe this is not an issue, but if not, you must handle this issue manually.

In this article I will talk about aspect ratio conservation and automatic scaling for 2D games on OpenGL, this will help keep thing in place and help artist design everything to a specific aspect ratio.

Code will be applied to an OpenGL environment but the concept can be applied to any framework/engine that lets you modify the viewport.

  1. //Set this to the desired aspect ratio.
  2. float targetAspectRatio = 16.f/9.f;
  3. //This can be your window resolution or if running in full screen
  4. //the screen native resolution.
  5. int renderWidth = 1024;
  6. int renderHeight = 768;
  7. //Save the current aspect ratio for later use
  8. float currentAspectRatio = (float)renderWidth / (float)renderHeight;
  9. //Now we calculate the biggest possible area that fits using the
  10. //targetAspectRatio
  11. int width = renderWidth;
  12. int height = (int)(width / targetAspectRatio);
  13. if (height > renderHeight)
  14. {
  15. //It doesn't fit, change to pillarbox.
  16. height = renderHeight;
  17. width = (int)(height * targetAspectRatio);
  18. }
  19. //Now get the new viewport size
  20. int vp_x = (renderWidth / 2) - (width / 2);
  21. int vp_y = (renderHeight / 2) - (height / 2);
  22. int vp_with = width + vp_x;
  23. int vp_height = height + vp_y;
  24. //In this step we can already set the new viewport
  25. glViewport(vp_x, vp_y, vp_width, vp_height);
  26. //Now we have to get the scaling factor by which all geometry should
  27. //be scaled, for this we define a design resolution, which is the
  28. //resolution you designed your game for
  29. int designWidth = 1280;
  30. int designHeight = 720;
  31. float scaleCorrectionX = vp_width / designWidth ;
  32. float scaleCorrectionY = vp_height / designHeight;
  33. //Apply this scaling to all your object and you are done