【问题标题】:How to count down both cooldown and duration如何计算冷却时间和持续时间
【发布时间】:2019-11-11 16:59:18
【问题描述】:

在我正在开发的一个小型模拟游戏(A.I.太空飞船射击游戏)中,我试图想出一个有效的盾牌功能或 IEnumerator,它可以被调用或启动并做多种事情:

  • 如果护盾的冷却时间高于零,则倒计时
  • 如果冷却时间结束,则在设定的持续时间(5 秒)内激活护盾
  • 持续时间结束后停用护盾

但是,我在仅使用 Ienumerator 进行尝试时遇到了一些问题。我之前可以使用 IEnumerators 倒计时和冷却时间,但尝试同时进行冷却时间和持续时间似乎不起作用,因为 Unity 不允许我在不离开 IEnumerator 的情况下进行两次 WaitForSeconds。

同样,每艘船都有一个炮塔,炮塔内部是一个 IEnumerator,它会发射或倒计时冷却时间,视情况而定。

// Fire continuously if in range and we have more than 1 shot left
    // Otherwise, reload for (rate) seconds and reset shots left
    public IEnumerator Fire(Vector2 target) {
        firing = true;

        if (cooldown <= 0) {
            if (bullets > 0) {
                // Fire a bullet
                bullets--;

                // Instatiate the bullet
                }
            } else {
                // Reload
                cooldown = rate;
                bullets = count;
            }
        } else {
            yield return new WaitForSeconds(1);
            cooldown--;
        }

        firing = false;
        yield break;
    }

使用firing标志调用Fire协程,检查它是否正在运行,如果没有调用

var fire = turret.Fire(shootTarget + offset);
if (!turret.firing && InRange() == true) {
    StartCoroutine(fire);
}

如果船还活着并且我们有一个目标,则每隔一秒左右。

我确实认为不建议我目前使用 IEnumerator,因为它必须至少每秒调用一次,但目前环境有多小,这似乎不是问题。

感谢任何帮助。

【问题讨论】:

  • 发射子弹状态不等待时间,所以你会在一帧内发射所有子弹
  • 你在哪里/如何调用你的协程?也请为 Shields 添加IEnumerator...
  • @derHugo 我在问题中添加了一些额外的代码,看看是否有帮助。
  • 我的问题是:这是否只调用一次,例如在OnTriggerEnter 中,或者它是否像每一帧一样被调用,例如在Update?
  • @derHugo 在调用函数Shoot() 的 InvokeRepeating 中调用它,该函数确定飞船是否还活着,是否在目标范围内,并且当前没有射击。该函数大约每秒重复一次。

标签: c# unity3d 2d repeat ienumerator


【解决方案1】:

没有协程的快速代码,不知道它是否在游戏中工作。不过应该能给你一些想法,我希望。

public class Shield : MonoBehaviour {

public float duration;
public float cooldown;
public float lastActivated;
public bool IsActivated => (lastActivated - (Time.time - duration)) > 0;
public bool onCoolDown => (lastActivated - (Time.time - cooldown)) > 0;

public void Activate(){
if(onCoolDown) return;

lastActivated = Time.time;
}

void LateUpdate(){
if(IsActivated) //Show shield effects, blahblah
else //Do nothing, blahblah
}

}

【讨论】:

    猜你喜欢
    • 2021-05-15
    • 2013-03-07
    • 1970-01-01
    • 2016-01-18
    • 2011-07-30
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多