【问题标题】:Why is onTap method not working in flame?为什么 onTap 方法在火焰中不起作用?
【发布时间】:2020-09-29 10:28:30
【问题描述】:

我正在尝试使用火焰和颤振重新创建游戏中的飞鸟,但我遇到了一个问题,我想知道是否有人可以帮助我。

问题是 onTap 方法不起作用。这是我的代码:

const COLOR = const Color(0xFF75DA8B);
const SIZE = 52.0;
const GRAVITY = 400.0;
const BOOST = -380.0;

void main() async{
  WidgetsFlutterBinding.ensureInitialized ();
  final size = await Flame.util.initialDimensions();
  final game = MyGame(size);
  runApp(game.widget);
}

class Bg extends Component with Resizable{
  static final Paint _paint = Paint()..color = COLOR;
  @override
  void render(Canvas c) {
    c.drawRect(Rect.fromLTWH(0.0, 0.0, size.width, size.height), _paint);
  }

  @override
  void update(double t) {
  }

}


class Bird extends AnimationComponent with Resizable{
  double speedY = 0.0;
  bool frozen;
  Bird () : super.sequenced(SIZE, SIZE, 'bird.png', 4, textureWidth: 16.0, textureHeight: 16.0) {
    this.anchor = Anchor.center;
  }

  Position get velocity => Position (300.0, speedY);


  reset () {
    this.x = size.width/ 2;
    this.y = size.height/2;
    speedY = 0;
    frozen = true;
    angle = 0.0;
  }

  @override
  void resize(Size size) {
    super.resize(size);
    reset();
  }

  @override
  void update(double t) {
  super.update(t);
    if (frozen) return;
    this.y += speedY * t - GRAVITY * t * t / 2;
    this.speedY += GRAVITY * t;
    this.angle = velocity.angle();
    if (y > size.height) {
      reset();
    }
  }
  onTap () {
    if (frozen) {
      frozen = false;
      return;
    }
    speedY = (speedY + BOOST).clamp(BOOST, speedY);
  }

}


class MyGame extends BaseGame {

  Bird bird;
  MyGame (Size size){
    add(Bg());
    add(bird = Bird());
  }
  @override
  void onTap() {
    bird.onTap();
  }
}

小鸟保持静止,如果我注释这行代码:

如果(冻结)返回; 在更新方法上,然后它会下降但 ontap 不起作用。

你知道为什么吗?

非常感谢您。

【问题讨论】:

    标签: flutter flame


    【解决方案1】:

    我不知道您使用的是哪个版本的 Flame,因为这是一个很老的问题。如果您现在使用的是 1.0.0 的候选版本,您至少应该遵循以下结构:

    class MyGame extends BaseGame with HasTapableComponents {
      Future<void> onLoad() async {
        // Load images and sprites etc
        add(MyComponent());
      }
      ... your game code
    }
    
    class MyComponent extends SpriteAnimationComponent with Tapable {
      ...
    
      @override
      bool onTapUp(TapUpInfo event) {}
    
      @override
      bool onTapDown(TapDownInfo event) {}
    
      @override
      bool onTapCancel() {}
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 2019-07-18
      • 2020-10-02
      • 2011-03-04
      相关资源
      最近更新 更多