kurtome / leap

An opinionated toolkit for creating 2D platformers on top of the Flame engine.
https://pub.dev/packages/leap
MIT License
43 stars 8 forks source link

Add option to reset the map #58

Open ricardodalarme opened 2 weeks ago

ricardodalarme commented 2 weeks ago

I would like to have an easy way to reset the map.

My use case is this: when the player dies, he respawns at the starting position and the map SHOULD be reset.

Right now, there is no easy way to do this. So having a .reset() like function inside the LeapMap would help a lot.

kurtome commented 2 weeks ago

The pattern I've been using for this is to reload the map in the Game class and add:

class MyGame {
  ...

  Future<void> reloadLevel() async {
    await loadWorldAndMap(
      tiledMapPath: 'map.tmx',
      tiledObjectHandlers: tiledObjectHandlers,
    );

    // Don't let the camera move outside the bounds of the map, inset
    // by half the viewport size to the edge of the camera if flush with the
    // edge of the map.
    final inset = camera.viewport.virtualSize;
    camera.setBounds(
      Rectangle.fromLTWH(
        inset.x / 2,
        inset.y / 2,
        leapMap.width - inset.x,
        leapMap.height - inset.y,
      ),
    );
  }

  @override
  void onMapUnload(LeapMap map) {
    player?.removeFromParent();
  }

  @override
  void onMapLoaded(LeapMap map) {
    if (player != null) {
      world.add(player!);
      player!.resetPosition();
    }
  }
}

And make sure to call game.reloadLevel() from the Player when the player dies