我在游戏中创造了一个玩家,当你按住空格键时它便会进入慢动作。但我希望玩家每次只能出现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
来运行与时间相关的方法。方法说明如下:
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;
}
此外,还需要考虑不在定时器中的条件。
if (Input.GetKeyDown(KeyCode.Space) && !inTimer)
{
StartCoroutine(StartTimer()); // how to run timer
}