I am using a coroutine to animate the fading effect on my objects material.
public IEnumerator DissolveIn()
{
float elapsed = 0f;
while (elapsed < 1)
{
elapsed += Time.deltaTime;
for (int i = 0; i < 7; i++)
{
Material mat = transform.GetChild(i).GetComponent<SpriteRenderer>().material;
float fade = math.lerp(mat.GetFloat("_Fade"), .8f, .22f);
mat.SetFloat("_Fade", fade);
}
yield return null;
}
for (int i = 0; i < 7; i++)
{
Material mat = transform.GetChild(i).GetComponent<SpriteRenderer>().material;
mat.SetFloat("_Fade", 1f);
}
}
The problem is the speed of the animation is changing with the fps changes. If someone plays the game with 30 fps the animation becomes slow. And for someone with 200 fps it is too fast to even see what is happening.
Is there any way for me to make this fps independent?
>Solution :
Don’t use delta time, but compute elapsed based on the animation’s start time and the current time, something like this. You can also get rid of the final for loop by doing it within the animation loop:
public IEnumerator DissolveIn()
{
float startTime = Time.time;
while (true)
{
float elapsed = Math.min(1, Time.time - startTime);
for (int i = 0; i < 7; i++)
{
Material mat = transform.GetChild(i).GetComponent<SpriteRenderer>().material;
float fade = math.lerp(mat.GetFloat("_Fade"), .8f, .22f);
mat.SetFloat("_Fade", fade);
}
if (elapsed >= 1)
break;
yield return null;
}
}