Search code examples
flutterdartflame

Flutter Flame: proper Viewport to match the screen size


How can I find out the screen size and place my game item according to screen resolution? I want to run my game on the web client.

component outside of the screen

I want to resize my red game component so fit in the screen and position in center.
LibGdx has some good java class for this concept: Link


Solution

  • You can use a FixedResolutionViewport and set it to the smallest edge if you always want it as a square.

    With the CameraComponent

    class MyGame extends FlameGame {
      Future<void> onLoad() async {
        double maxSide = min(size.x, size.y);
        final cameraComponent = CameraComponent.withFixedResolution(
          world: myWorldComponent,
          width: maxSide,
          height: maxSide,
        );
        ...
      }
    }
    

    or

    class MyGame extends FlameGame {
      Future<void> onLoad() async {
        final cameraComponent = CameraComponent(
          world: myWorldComponent,
          viewport: FixedAspectRatioViewport(aspectRatio: 1.0),
        );
        ...
      }
    }
    

    With the old Camera

    class MyGame extends FlameGame {
      Future<void> onLoad() async {
        double maxSide = min(size.x, size.y);
        camera.viewport = FixedResolutionViewport(Vector2.all(maxSide)); 
      }
    }
    

    If you want the game's (viewport) size inside of another component you can add the HasGameRef mixin and use the game's size variable in the same way:

    class MyComponent extends Component with HasGameRef {
        MyComponent() : super(anchor: Anchor.center);
    
      Future<void> onLoad() async {
        final gameSize = gameRef.size;
        // To add a position component in the center of the screen for example:
        // (when the camera isn't moved)
        position = gameSize/2;
      }
    }
    

    If you want other sizes I recommend to look at game.camera and game.camera.viewport which offers a few other options too.