如何检测点击 Flame 组件?

How to detect tap on Flame components?

我正在使用 Flutter 和 Flame (0.29.3) 构建一个简单的手机游戏。我正在尝试检测 PositionComponent/SpriteComponent 上的点击。但是,我没有这样做。 References/tutorials 正在使用 addGestureRecognizer,但已弃用。

我定义我的PositionComponent如下;

class Enemy extends PositionComponent with Tapable {
  Rect enemyRect;

  Enemy(double x, double y) {
    enemyRect = Rect.fromLTWH(x, y, 50, 50);
  }

  @override
  void render(Canvas c) {
    Color color = Color(0XFFFF0000);
    Paint enemyColor = Paint()..color = color;
    c.drawRect(enemyRect, enemyColor);
  }

  void update(double t) {}

  @override
  void onTapUp(TapUpDetails details) {
    print("tap up");
  }

  @override
  void onTapDown(TapDownDetails details) {
    print("tap down");
  }

  @override
  void onTapCancel() {
    print("tap cancel");
  }
}

并且,我将 PositionComponent 添加到我的游戏中。

class GameController extends BaseGame with HasTapableComponents {
  Size screenSize;
  double tileSize;
  Player player;
  Enemy enemy;
  TapableComponent a;

  GameController() {
    initialize();
  }

  void initialize() async {
    resize(await Flame.util.initialDimensions());
    add(enemy = Enemy(200, 200));
  }

  @override
  void render(Canvas c) {
    Rect background = Rect.fromLTWH(0, 0, screenSize.width, screenSize.height);
    Paint backgroundPaint = Paint()..color = Color(0xFFFAFAFA);
    enemy.render(c);
  }

  @override
  void update(double t) {}

  @override
  void resize(Size size) {
    screenSize = size;
    tileSize = screenSize.width / 10;
  }
}

但是,它不起作用,我是不是漏掉了什么?

我认为您的示例代码是 v1 代码和 0.29.3 的混合体,如果您尝试使用最新的 Flame 候选版本:1.0.0-rc8 那么以下应该有效:

class TapableSquare extends PositionComponent with Tapable {
  static final Paint _white = Paint()..color = const Color(0xFFFFFFFF);
  static final Paint _grey = Paint()..color = const Color(0xFFA5A5A5);


  TapableSquare({Vector2 position})
      : super(
          position: position ?? Vector2.all(100),
          size: Vector2.all(100),
        );

  @override
  void render(Canvas canvas) {
    super.render(canvas);
    canvas.drawRect(size.toRect());
  }

  @override
  bool onTapUp(TapUpDetails details) {...}

  @override
  bool onTapDown(TapDownDetails details) {...}

  @override
  bool onTapCancel() {...}
}

class TapablesGame extends BaseGame with HasTapableComponents {
  @override
  Future<void> onLoad() async {
    add(TapableSquare());
  }
}

摘自此example

编辑:要使其适用于 0.29.3,您应该在 Enemy class 中设置 positionsize,而不是构建您自己的矩形, Tapable 不知道那个矩形。