首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何检测火焰组件上的敲击?

如何检测火焰组件上的敲击?
EN

Stack Overflow用户
提问于 2021-03-14 17:02:53
回答 1查看 361关注 0票数 2

我正在使用Flutter and flame (0.29.3)来构建一个简单的手机游戏。我正在尝试检测PositionComponent/SpriteComponent上的点击。然而,我没有做到这一点。参考/教程正在使用addGestureRecognizer,但它已被弃用。

我定义我的PositionComponent如下;

代码语言:javascript
复制
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加入到我的游戏中。

代码语言:javascript
复制
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;
  }
}

但是,它不工作,我是不是遗漏了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-03-14 22:20:10

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

代码语言:javascript
复制
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类中设置positionsize,而不是构建你自己的rect,Tapable不能知道那个rect。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66622684

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档