简体   繁体   English

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

[英]Lerp between two values over time

I'm trying to reduce a float by a time value, i'm using Unity and stopping time Time.timeScale = 0f; 我正在尝试通过时间值减少浮点数,我正在使用Unity并停止时间Time.timeScale = 0f; so can not use Time.deltaTime so using 'Time.realtimeSinceStartup' in a while loop, i read in the master volume variable from a global script that the player can set in game between 0 - 1 so say i read in 0.6 and i want to lower the volume to 0 in 2 second how do i get the percentage to keep reducing the volume by ? 因此无法使用Time.deltaTime因此在while循环中使用“ Time.realtimeSinceStartup”,我从全局脚本读取了主音量变量,玩家可以在游戏中将其设置在0-1之间,所以说我以0.6读取并且我想要在2秒内将音量降低到0,我如何获得百分比以保持音量降低?

Here is my code .. 这是我的代码..

 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;
    }
}

Sorry i just can't get the 'volumePercentage' 抱歉,我无法获取“ volumePercentage”

Thanks. 谢谢。

I'm using Unity and stopping time Time.timeScale = 0f; 我正在使用Unity并停止时间Time.timeScale = 0f; so can not use Time.deltaTime so using 'Time.realtimeSinceStartup' in a while loop. 因此不能使用Time.deltaTime ,而在while循环中使用'Time.realtimeSinceStartup'。

You don't need to use Time.realtimeSinceStartup for this. 您无需为此使用Time.realtimeSinceStartup It is true that setting Time.timeScale to 0 makes Time.deltaTime to return 0 every frame. 的确,将Time.timeScale设置为0会使Time.deltaTime每帧返回0

This is why Time.unscaledDeltaTime was added in Unity 4.5 to address that. 这就是为什么在Unity 4.5中添加了Time.unscaledDeltaTime来解决该问题的原因。 Simply replace the Time.deltaTime with Time.unscaledDeltaTime . 只需将Time.deltaTime替换为Time.deltaTime Time.unscaledDeltaTime You can event use if (Time.timeScale == 0) to automatically decide whether to use Time.unscaledDeltaTime or Time.deltaTime . 您可以使用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;
    }
}

Usage : 用法

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

The value changes from 5 to 1 within 3 seconds. 该值在3秒钟内从5变为1 It doesn't matter if Time.timeScale is set to 1 or 0 . Time.timeScale设置为1还是0都没有关系。

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

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