You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Flame:如何让敌方植物稀疏发射子弹

解决植物连续射击问题,实现间隔发射

核心方案

添加射击冷却计时器,通过累计帧时间控制射击间隔:只有当距离上次射击的时间达到设定时长时,才允许发射子弹,同时重置计时器。

代码修改步骤

  1. 在植物类中添加冷却相关的成员变量:
// 设定射击冷却时长(单位:秒,可按需调整)
final double _shootCooldown = 2.0;
// 记录距离上次射击的累计时间
double _shootTimer = 0.0;
  1. 修改update方法,控制射击触发时机:
@override
void update(double dt) {
  if (!gotStomped) {
    _updateState();
    // 累加每帧的时间差
    _shootTimer += dt;

    if (playerInRange()) {
      current = State.attack;
      // 累计时间达标时才触发射击
      if (_shootTimer >= _shootCooldown) {
        _shoot();
        _shootTimer = 0.0; // 重置计时器
      }
    } else {
      current = State.idle;
      _shootTimer = 0.0; // 玩家离开射程后重置计时器
    }
  }
  super.update(dt);
}
  1. 保持_shoot方法的发射逻辑不变(如需多发射击可看下方优化):
void _shoot() {
  moveDirection = lerpDouble(moveDirection, tragetDirection, 0.1) ?? 1;

  double playerOffset = (player.scale.x > 0) ? 0 : -player.width;
  double chickenOffset = scale.x > 0 ? 0 : -width;

  tragetDirection =
      (player.x + playerOffset < position.x + chickenOffset) ? -1 : 1;
  Bullet bullet = Bullet(
      position: Vector2(position.x, position.y),
      size: Vector2.all(16),
      tragetDirection: tragetDirection);

  parent?.add(bullet);
}

可选优化:实现“每几秒发射1-2发”

如果需要每次触发时随机发射1-2发,可以把发射逻辑抽离,增加随机判断:

// 替换原_shoot方法,拆分发射逻辑
void _shoot() {
  // 发射第一发
  _fireSingleBullet();
  // 50%概率追加一发(可调整概率)
  if (Random().nextDouble() > 0.5) {
    // 延迟0.2秒发射第二发,避免两发完全重叠
    Future.delayed(const Duration(milliseconds: 200), () {
      if (!gotStomped && playerInRange()) {
        _fireSingleBullet();
      }
    });
  }
}

// 单独的单发射击方法
void _fireSingleBullet() {
  moveDirection = lerpDouble(moveDirection, tragetDirection, 0.1) ?? 1;
  current = State.attack;

  double playerOffset = (player.scale.x > 0) ? 0 : -player.width;
  double chickenOffset = scale.x > 0 ? 0 : -width;

  tragetDirection =
      (player.x + playerOffset < position.x + chickenOffset) ? -1 : 1;
  Bullet bullet = Bullet(
      position: Vector2(position.x, position.y),
      size: Vector2.all(16),
      tragetDirection: tragetDirection);

  parent?.add(bullet);
}

调整后,植物会在玩家进入射程后,每2秒触发一次射击,每次射击随机发射1-2发子弹,彻底解决持续连发的问题。

内容的提问来源于stack exchange,提问作者rikeelesh ramjattun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 07:52:52