Lerp between two values over time

眉间皱痕 提交于 2019-12-01 07:29:47

问题


I'm trying to reduce a float by a time value, i'm using Unity and stopping time 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 ?

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'

Thanks.


回答1:


I'm using Unity and stopping time Time.timeScale = 0f; so can not use Time.deltaTime so using 'Time.realtimeSinceStartup' in a while loop.

You don't need to use Time.realtimeSinceStartup for this. It is true that setting Time.timeScale to 0 makes Time.deltaTime to return 0 every frame.

This is why Time.unscaledDeltaTime was added in Unity 4.5 to address that. Simply replace the Time.deltaTime with Time.unscaledDeltaTime. You can event use if (Time.timeScale == 0) to automatically decide whether to use Time.unscaledDeltaTime or 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. It doesn't matter if Time.timeScale is set to 1 or 0.



来源:https://stackoverflow.com/questions/49750245/lerp-between-two-values-over-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!