- Home /
This post has been wikified, any user with enough reputation can edit it.
Question by
WinterboltGames · Feb 28, 2020 at 05:25 PM ·
color changegradientcolor.lerp
How does Gradient.Evaluate work internally?
I have been trying to make a structure similar to Unity's built-in Gradient
.
What I'm stuck at getting my head around is the Gradient.Evaluate
function, how does it work internally?
Any code snippets will be really helpful!
Comment
Best Answer
Answer by Namey5 · Feb 28, 2020 at 09:51 PM
I would imagine it's a combination of lerps between colours based on their time values, but for simplicity's sake it can be done with one lerp, i.e;
Color EvaluateGradient (float t, GradientColorKey[] keys)
{
//We can early exit if t is at the boundaries
if (t <= keys[0].time)
return keys[0].color;
if (t >= keys[keys.Length - 1].time)
return keys[keys.Length - 1].color;
//Loop through each gradient segment
for (int i = 0; i < keys.Length - 1; i++)
{
//Find the start and end keys of this segment
GradientColorKey startKey = keys[i];
GradientColorKey endKey = keys[i + 1];
//We only need to do any work if t is in the current segment
if (t < endKey.time)
{
//Find t in relation to the current segment
float localTime = Mathf.Clamp01 ((t - startKey.time) / (endKey.time - startKey.time));
return Color.Lerp (startKey.color, endKey.color, localTime);
}
}
//We will only get here if the last key is placed early, so return that
return keys[keys.Length - 1].color;
}
I should also note that the above will only work if the keys are in order (ascending based on time). If they aren't, you can sort them;
public static void Sort$$anonymous$$eys (ref GradientColor$$anonymous$$ey[] keys)
{
for (int i = 0; i < keys.Length; i++)
{
for (int j = i + 1; j < keys.Length; j++)
{
if (keys[j].time < keys[i].time)
{
GradientColor$$anonymous$$ey tmp = keys[i];
keys[i] = keys[j];
keys[j] = tmp;
}
}
}
}