Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect a swipe in a game with flutter/flame

I want to create a game in flutter with flame. For this game I want to detect swipes.

I could implement a tap recognition with the help of a tutorial. But I could not implement it with swipe detection.

my main with Taprecognition looks like this: My main function is

void main() async{
  Util flameUtil = Util();
  await flameUtil.fullScreen();
  await flameUtil.setOrientation(DeviceOrientation.portraitUp);

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

  TapGestureRecognizer tapper = TapGestureRecognizer();
  tapper.onTapDown = game.onTapDown;
  flameUtil.addGestureRecognizer(tapper);
}

In my GameManager class I do have:

class GameMAnager extends Game{
  // a few methods like update, render and constructor
  void onTapDown(TapDownDetails d) {
    if (bgRect.contains(d.globalPosition)) { //bgRect is the background rectangle, so the tap works on the whole screen
      player.onTapDown();
    }
  }

And my player class contains:

  void onTapDown(){
    rotate();
  }

Now I want to change this to rotate in the direction of the swipe instead of onTapDown. I tried to somehow add

  GestureDetector swiper = GestureDetector();
  swiper.onPanUpdate = game.onPanUpdate;

to my main and

  void onPanUpdate() {

  }

to my gameManager class. But I cannot find anything similar to TapDownDetails for panning.

Any suggestions on this?

I saw some help for this to wrap the widget in a GestureDetector and use it like this:

GestureDetector(onPanUpdate: (details) {
  if (details.delta.dx > 0) {
    // swiping in right direction
  }
});

But I couldn't make it work on my project.

like image 875
ChrizZlyBear Avatar asked Nov 17 '25 02:11

ChrizZlyBear


1 Answers

You can use the HorizontalDragGestureDetector (or PanGestureRecognizer if you need both axes) use the following in your main method

HorizontalDragGestureRecognizer tapper = HorizontalDragGestureRecognizer();
tapper.onUpdate = game.dragUpdate;

and then the following in your GameManager

void dragUpdate(DragUpdateDetails d) {
    // using d.delta you can then track the movement and implement your rotation updade here
}

That should do the trick :D

like image 51
Marco Papula Avatar answered Nov 20 '25 03:11

Marco Papula



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!