2

我正在使用 Flutter 和 Flame (0.29.3) 构建一个简单的手机游戏。我正在尝试检测 PositionComponent/SpriteComponent 上的点击。但是,我没有这样做。参考/教程正在使用 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;
  }
}

但是,它不起作用,我错过了什么吗?

4

1 回答 1

1

我认为您的示例代码是 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());
  }
}

从这个例子中提取。

编辑:为了让它对你有用,0.29.3你应该在你的课堂上设置position,而不是建立你自己的矩形,不知道那个矩形。sizeEnemyTapable

于 2021-03-14T14:20:09.730 回答