Why onTap is not working in my flame game (Flutter)?

861 Views Asked by At

I am working on a simple game using Flame and Flutter. I am following this tutorial: Create a Mobile Game with Flutter and Flame – Beginner Tutorial

But after I added some code following tutorial line:

flameUtil.addGestureRecognizer(tapper); 

appears underlined and onTap function is not working.

2

There are 2 best solutions below

0
On

API of flutter-flame library is constantly evolving and the solution from tutorial above might not work anymore.

I had some hard times to re-implement example from this presentation: https://www.youtube.com/watch?v=sFpjEH-ok2s, so you're not alone :-)

Newer versions of flutter-flame like 0.23.0, requires to make it work to add TapDetector mixin to your BaseGame class like below:

class MyBaseGame extends BaseGame with TapDetector, DoubleTapDetector {
  @override
  void onTapDown(_) {
    add(RenderedTimeComponent(Timer(1)..start()));
  }

  @override
  void onDoubleTap() {
    add(RenderedTimeComponent(Timer(5)..start()));
  }
}

Source: https://github.com/flame-engine/flame/blob/00ad86eb63aa54b411f1d080fec501dd7b671a81/doc/examples/timer/lib/main.dart

Thanks to this your code of BoxGame initialization is just:

BoxGame game = BoxGame();
runApp(game.widget);

without declarations of Util and TapGestureRecognizer.

1
On

You can use TapDetector mixin:

class WarriorGirlGame extends FlameGame with TapDetector { @override void onTapDown(TapDownInfo info) { ... } }