随着时间的推移在两个值之间变小 [英] Lerp between two values over time
问题描述
我正在尝试将浮点数减少一个时间值,我正在使用Unity并停止时间Time.timeScale = 0f;
,所以不能使用Time.deltaTime
,所以在while循环中使用了'Time.realtimeSinceStartup',我在玩家可以在游戏中设置的全局脚本中的主音量变量,介于0-1之间,所以说我读0.6,我想在2秒内将音量降低到0,我如何获得百分比以保持音量减小?
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 useTime.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.
这就是为什么在 Unity 4.5中添加了 Time.unscaledDeltaTime
的原因来解决这个问题.只需将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
.
这篇关于随着时间的推移在两个值之间变小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!