- Home /
{Solved}Trying to add color loop to background using Vector4
This is what I have so far. It currently works on the Game Object I apply the script to. I'm just trying to make it so that the Vector4.Lerp works back and forth without stopping. Please help.
#pragma strict
private var backgroundColorMagenta : Color = Color.magenta;
private var backgroundColorGreen : Color = Color.green;
private var backgroundColorRed : Color = Color.red;
Color background = new Color(1f,0.83f,0f,1f)
function Start () {
}
function Update () {
renderer.material.color = Color.Lerp(Vector4(0.82,0,1,1), Vector4(1,0.83,0,1), 0.05 * Time.time);
if (this.gameObject.renderer.material.color == background)
{
{renderer.material.color = Color.Lerp(Vector4(1,0.83,0,1), Vector4(0.82,0,1,1), 0.05 * Time.time);
}
}
}
Answer by whydoidoit · Mar 11, 2014 at 06:05 PM
So you need a function to convert Time.time into a value that rises and falls between 0 and 1.
function pingPong(t: float) : float {
t = Mathf.Repeat(t, 2);
return t < 1 ? t : 2 - t;
}
then
renderer.material.color = Color.Lerp(Vector4(1,0.83,0,1), Vector4(0.82,0,1,1), pingPong(0.05 * Time.time))
That's exactly what I was looking for!! The only problem now is the background color doesn't restart a second time. It goes from the Vector4(1,0.83,0,1) to the other one, and back to the Vector4(1,0.83,0,1) but doesn't start again. It simply stays at that color. Any way to loop it infinitely?
Answer by SirCrazyNugget · Mar 11, 2014 at 11:11 PM
Change the pingPong function to:
C#
float v = t % 2;
return v < 1 ? v : 2 - v;
Javascript
var v : float = t % 2;
return v < 1 ? v : 2 - v;
whydoidoit's version ensures it's between 0 and 2 but and stores it as v but then never returns v only t. AFAIK Modulo is faster than Mathf.Repeat too even though it's minimal, saving every process you can is always best.
also, after changing it. I got the annoying "Unexpected token: <" error.
Sorry, I posted in C#
var v : float = t % 2;
return v < 1 ? v : 2 - v;