繁体   English   中英

随着时间的推移在两个值之间变小

[英]Lerp between two values over time

我正在尝试通过时间值减少浮点数,我正在使用Unity并停止时间Time.timeScale = 0f; 因此无法使用Time.deltaTime因此在while循环中使用“ Time.realtimeSinceStartup”,我从全局脚本读取了主音量变量,玩家可以在游戏中将其设置在0-1之间,所以说我以0.6读取并且我想要在2秒内将音量降低到0,我如何获得百分比以保持音量降低?

这是我的代码..

 private IEnumerator VolumeDown ()
{
    float volumeIncrease = globalVarsScript.musicVolume;
    float volumePercentage = ??;
    float newLerpEndTime = Time.realtimeSinceStartup + 2f;

    while (Time.realtimeSinceStartup < newLerpEndTime)
    {
        audio.volume = volumeIncrease;
        volumeIncrease -= volumePercentage;
        yield return null;
    }
}

抱歉,我无法获取“ volumePercentage”

谢谢。

我正在使用Unity并停止时间Time.timeScale = 0f; 因此不能使用Time.deltaTime ,而在while循环中使用'Time.realtimeSinceStartup'。

您无需为此使用Time.realtimeSinceStartup 的确,将Time.timeScale设置为0会使Time.deltaTime每帧返回0

这就是为什么在Unity 4.5中添加了Time.unscaledDeltaTime来解决该问题的原因。 只需将Time.deltaTime替换为Time.deltaTime Time.unscaledDeltaTime 您可以使用if (Time.timeScale == 0)事件来自动决定是使用Time.unscaledDeltaTime还是Time.deltaTime

IEnumerator changeValueOverTime(float fromVal, float toVal, float duration)
{
    float counter = 0f;

    while (counter < duration)
    {
        if (Time.timeScale == 0)
            counter += Time.unscaledDeltaTime;
        else
            counter += Time.deltaTime;

        float val = Mathf.Lerp(fromVal, toVal, counter / duration);
        Debug.Log("Val: " + val);
        yield return null;
    }
}

用法

StartCoroutine(changeValueOverTime(5, 1, 3));

该值在3秒钟内从5变为1 Time.timeScale设置为1还是0都没有关系。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM