Search code examples
flutterflame

How to detect screen boundaries with Flame in Flutter?


I want to detect when an object goes outside of the screen in Flame Flutter. I think there is two way to accomplish this either with Collidable mixin or with Forge2D. If possible explain it in both of them.

Flame version: flame: 1.0.0-releasecandidate.18


Solution

  • It is way overkill to use Forge2D for this (that complicates a lot of other things too). But you can use the built-in collision detection system, or you can check in the update-loop whether it is within the screen or not (this would be the most efficient).

    By using the collision detection system we can use the built-in ScreenCollidable and you can do something like this:

    class ExampleGame extends FlameGame with HasCollidables {
      ...
      @override
      Future<void> onLoad() async {
        await super.onLoad();
        add(ScreenCollidable());
      }
    }
    
    class YourComponent extends PositionComponent with HasHitboxes, Collidable {
      @override
      Future<void> onLoad() async {
        await super.onLoad();
        // Change this if you want the components to collide with each other
        // and not only the screen.
        collidableType = CollidableType.passive;
        addHitbox(HitboxRectangle());
      }
    
      // Do note that this doesn't work if the component starts
      // to go outside of the screen but then comes back.
      @override
      void onCollisionEnd(Collidable other) {
        if (other is ScreenCollidable) {
          removeFromParent();
        }
      }
    }
    

    and by just calculating it in the update-loop:

    class YourComponent extends PositionComponent with HasGameRef {
      @override
      void update(double dt) {
        final topLeft = absoluteTopLeftPosition;
        final gameSize = gameRef.size;
        if(topLeft.x > gameSize.x || topLeft.y > gameSize.y) {
          removeFromParent();
          return;
        }
        final bottomRight = absolutePositionOfAnchor(Anchor.bottomRight);
        if(bottomRight.x < 0 || bottomRight.y < 0) {
          removeFromParent();
          return;
        }
      }
    }
    

    I also recommend that you update to Flame 1.0.0 now when it is released. :)