Search code examples
flutterflame

Flutter / Flame - How to work with PanDetector and other GestureDetector for Components at same time?


My game uses PanDetector to move the player.

class MyGame extends BaseGame with PanDetector, HasTapableComponents {


  @override
  void onPanUpdate(DragUpdateDetails details) {

    // move the player
   player.move(details.delta.dx, details.delta.dy);

    super.onPanUpdate(details);
  }


}

I needed to add a pause button on the top-right of the screen.

class PauseComponent extends PositionComponent with Tapable, HasGameRef<MyGame>{

  Rect rect;
  Sprite spritePause = Sprite("pause_button.png");

  PauseComponent(){

    rect = Rect.fromLTWH(
        Get.find<Config>().screenSize.width * 0.92,
        Get.find<Config>().screenSize.height * 0.04,
        Get.find<Config>().screenSize.width * 0.05,
        Get.find<Config>().screenSize.height * 0.10);

  }

  @override
  void render(Canvas c) {

    spritePause.renderRect(c, rect);

  }

  @override
  void onTapDown(TapDownDetails details) {

    if(gameRef.gameState == GameState.PLAYING){

      gameRef.gameState = GameState.PAUSED;
      gameRef.pauseEngine();

    } else {

      gameRef.gameState = GameState.PLAYING;
      gameRef.resumeEngine();

    }

    print("STATUS: ${gameRef.gameState}");

    super.onTapDown(details);
  }
}

But it's not working, how can I make the PauseComponent's onTapDown work, use PanDetector and some other Detector to the PauseComponent?


Solution

  • I used addWidgetsOverlay mixin and added a Pause Button custom widget since PanDetector was not working with Tapable.

    import 'package:flutter/material.dart';
    
    class PauseButton extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Align(
          alignment: Alignment.topRight,
          child: Material(
            color: Colors.blue,
            child: IconButton(
              icon: Icon(Icons.pause),
              onPressed: (){
                print("TOUCH!");
              },
            ),
          ),
        );
      }
    }
    

    And removing HasTapableComponents mixin (not sure if it was conflicting with anything), now it's working.

    class MyGame extends BaseGame with HasWidgetsOverlay, PanDetector {
    
      MyGame(){
    
      addWidgetsOverlay("Pause Button", PauseButton());
    
    
     }
    
    }