慢动作时间限制

Slowmotion time limit

我在我的游戏中制作了一个播放器,当您按住 space 条时它会进入慢动作。但我希望播放器一次只能以慢动作播放 5 秒。 10 秒后玩家将可以再次进入慢动作。

这是脚本的代码

using UnityEngine;

public class SlowMotion : MonoBehaviour
{
    public float slowMotionTimescale;

    private float startTimescale;
    private float startFixedDeltaTime;

    void Start()
    {
        startTimescale = Time.timeScale;
        startFixedDeltaTime = Time.fixedDeltaTime;
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            StartSlowMotion();
        }

        if (Input.GetKeyUp(KeyCode.Space))
        {
            StopSlowMotion();
        }
    
    }

    private void StartSlowMotion()
    {
        Time.timeScale = slowMotionTimescale;
        Time.fixedDeltaTime = startFixedDeltaTime * slowMotionTimescale;
    }

    private void StopSlowMotion()
    {
        Time.timeScale = startTimescale;
        Time.fixedDeltaTime = startFixedDeltaTime;
    }
}

您可以使用IEnumerator到运行time-dependent方法。方法说明如下:

public bool inTimer; // are slow motion is in timer?
public IEnumerator StartTimer()
{
    inTimer = true;
    
    StartSlowMotion();
    
    yield return new WaitForSeconds(5f); // wait to end slow motion

    StopSlowMotion();
    
    yield return new WaitForSeconds(5f); // wait time to finish
    
    inTimer = false;
}

另外还需要考虑不在timer中的情况

if (Input.GetKeyDown(KeyCode.Space) && !inTimer)
{
    StartCoroutine(StartTimer()); // how to run timer
}