Flutter Flame: proper Viewport to match the screen size
Emily Wong
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.
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
1 Answer
You can use the FixedResolutionViewport and set it to the smallest edge if you always want it as a square:
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.