随着时间的推移,两个值之间的 Lerp [英] Lerp between two values over time

查看:15
本文介绍了随着时间的推移,两个值之间的 Lerp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 ?

这是我的代码..

 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"

Sorry i just can't get the 'volumePercentage'

谢谢.

推荐答案

我正在使用 Unity 并停止时间 Time.timeScale = 0f; 所以不能使用Time.deltaTime 所以在 while 循环中使用Time.realtimeSinceStartup".

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

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

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.

这就是为什么 Time.unscaledDeltaTimeUnity 4.5 中添加来解决这个问题.只需将 Time.deltaTime 替换为 Time.unscaledDeltaTime.您可以使用if (Time.timeScale == 0)自动决定是使用Time.unscaledDeltaTime还是Time.deltaTime.>

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

用法:

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

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

The value changes from 5 to 1 within 3 seconds. It doesn't matter if Time.timeScale is set to 1 or 0.

这篇关于随着时间的推移,两个值之间的 Lerp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆