- Home /
Smooth gradient between colours?
I'm making a day/night cycle that's tied to the user's real time (obtained via DateTime.Now
).
For testing purposes, my sky graphics are tied to the seconds count from DateTime
. A full day is 60 seconds. I created a gradient with colours set at various intervals and I'm calling it from Update()
via gradient.Evaluate(gradientCounter)
, where gradientCounter
is the current time in seconds divided by 60.
However, this means that the sky colour is only updated every second, not every frame. To fix this, I tried adding a Lerp to the bottom of Update()
, like this:
Color.Lerp(gradient.Evaluate(gradientCounter), gradient.Evaluate(nextGradientCounter), Time.deltaTime)
nextGradientCounter
is simply the current time in seconds, plus one, divided by 60.
But this attempt did not work, and the colour is still only changing every second. Does anyone know why the Lerp failed or if there's a better solution?
Answer by karl_ · Mar 26, 2015 at 05:30 PM
I think it's because DateTime.Second
is an integer - so dividing by 60 is just going to return 0. Here's an example using the DateTime.Millisecond
property to lerp from one end of the gradient to the other over a 1 second period:
using UnityEngine;
using System.Collections;
public class GradientTest : MonoBehaviour {
public Gradient gradient;
void OnGUI()
{
System.DateTime date = System.DateTime.Now;
GUI.color = gradient.Evaluate( date.Millisecond / 1000f );
GUILayout.Label("Hello, world!");
}
}
That works, but how would I convert it to a one-$$anonymous$$ute cycle? I can't just change 1000f
to 60000f
because the millisecond count gets reset every second. And I can't do date.Second / 60f
because then the colour only changes every second.
If you want it to be one cycle per $$anonymous$$ute would just do gradient.Evaluate( (date.Second * 1000f + date.$$anonymous$$illisecond) / (60f * 1000f) )
. So you take the seconds, convert that to milliseconds (seconds * 1000)
, add the current second's milliseconds, then divide by the total milliseconds in a $$anonymous$$ute (60 * 1000)
to normalize that value.
Your answer
Follow this Question
Related Questions
change Mesh.colors over time help? 2 Answers
Controlling duration of Color.Lerp in seconds 2 Answers
Color lerp once? 2 Answers
Gradient Background With Random Color Lerp 0 Answers
Time.deltaTime making color lerp appear fast, but won't reach 1 1 Answer