Skip to content

Responsive game

Mark Knol edited this page Jun 3, 2014 · 3 revisions

Since you probably are going to create a game for different screens, the project should be respond to these variable dimensions nicely. Responsive layouts should be created procedurally.

In practice you have some options:

  • If you don't create a fullscreen game, you could choose a fixed width/height, and define it in CSS.
  • Otherwise set the #container width/height to 100% using CSS in the html-template, and do scaling and reposition manually. This means you have to think that the width/height of the stage are very variable, since every screen has different dimensions/resolutions.

Designed for a certain size

A common approach, to have a nice scaled game, is to wrap the game into a container Entity with a Sprite attached. On resize (System.stage.resize) you rescale the container to make it fit for a target size. Inside the game container you can use sizes like designed (at "100%").

You could implement it like this:

function onResize()
{
    // iPhone 5 as target dimension
    var targetWidth = 1136; 
    var targetHeight = 640;

    // Specifies that the entire application be scaled for the specified target area while maintaining the original aspect ratio.
    var scale = FMath.min(System.stage.width / targetWidth, System.stage.height / targetHeight);
    if (scale > 1) scale = 1; // You could choose to never scale up.
   
    // re-scale and center the sprite of the container to the middle of the screen.
    _container.get(Sprite)
        .setScale(scale)
        .setXY((System.stage.width - targetWidth * scale) / 2, (System.stage.height - targetHeight * scale) / 2);

    // You can even mask so you cannot look outside of the container
    //_container.get(Sprite).scissor = new Rectangle(0, 0, targetWidth, targetHeight);
}

The good part of this approach is that is easy to design for, but also to understand; you can easily guess how the game fits on every screen and what is in the virtual viewport (if you want to create a fair game, this could be important)

A downside is that it rescales your assets (so can look a bit blurry/crispy), don't use pixelart it's not a big issue. With a zooming camera you also scale.
It also does not look that good in another orientation, so you have to create a creative solution for that. If you create an app, you could lock the orientation, but you cannot lock in a browser.

Clone this wiki locally