fluttercameraboundsflame

How to use CameraComponent.setBounds() in Flutter Flame?


I have a world and a player. My camera follows the player. The player can't go out the worlds bounds I had created, but camera can see what is behind the world borders(black screen).

I tried to add CameraComponent.setBounds(...) as mentioned in documentation. setBounds() function asks for bounds of type Shape?. What I have to pass here? Before flame update I used "worldBounds: Rect.fromLTRB(0, 0, _background.size.x, _background.size.y)" in camera.followComponent, but it got deprecated


Solution

  • This is yet to be fully implemented in the new camera system (see https://github.com/flame-engine/flame/issues/2601).

    Currently the only workaround is to calculate the bounds to be smaller than where the player can move, for example, if your world is based around (0, 0):

    import 'package:flame/experimental.dart'; // Gives you the Rectangle
    ...
    
    class MyGame extends FlameGame {
      @override
      Future<void> onLoad() async {
        final halfViewportSize = camera.viewport.size / 2;
        final worldSize = 1500; // Size from the center in each direction.
        cameraComponent.setBounds(
          Rectangle.fromCenter(
            center: Vector2.zero(),
            size: Vector2.all(worldSize) - halfViewportSize,
          ),
        );
      }
    }