- Home /
{Solved}Need help making infinite loop for color changing background using a Vector4.Lerp with Mathf PingPong variable.
Here's my script so far, I just need to make it so it loops infinitely. As of right now, it goes from one color, to another, then back, but stops. I need it to keep going back and forth.
#pragma strict
function Start () {
}
function Update () {
renderer.material.color = Color.Lerp(Vector4(0.82,0,1,1), Vector4(1,0.83,0,1), backgroundLoop(0.1 * Time.time));
}
function backgroundLoop(t: float) : float
{
var v = Mathf.Repeat(t, 2);
return t < 1 ? t : 2 - t;
}
robertbu already mentioned $$anonymous$$athf.PingPong which is the easiest solution. However the proplem in your "custom" pingpong implementation is that you don't use your "v" variable but your "t". That's why it "stops" after the first ping pong. You do not use the repeated value. So you want to simply do:
t = $$anonymous$$athf.Repeat(t, 2);
ins$$anonymous$$d of
var v = $$anonymous$$athf.Repeat(t, 2);
ps: $$anonymous$$athf.PingPong does basically the same thing, just with a slightly different implementation:
// C#
public static float PingPong(float t, float length)
{
t = $$anonymous$$athf.Repeat(t, length * 2f);
return length - $$anonymous$$athf.Abs(t - length);
}
Answer by robertbu · Mar 11, 2014 at 11:38 PM
First off, Why use a Vector4? Just use a Color. Second, you can get it to cycle using either Mathf.PingPong() or Mathf.Sin() depending the feel you want. Sin will be more eased at the ends and often feels more natural:
#pragma strict
var speed : float = 1.0;
function Update () {
var t : float = (Mathf.Sin(Time.time * speed) + 1) / 2.0;
renderer.material.color = Color.Lerp(Color(0.82,0,1,1), Color(1,0.83,0,1), t);
}
And if you prefer Mahtf.PingPong() the calculation of 't' would be:
var t : float = Mathf.PingPong(Time.time * speed, 1.0);
Answer by KarlKarl2000 · Jan 19, 2017 at 04:51 AM
For those that arrive at this thread years later. A small update from my own use case.
RobertBu's answer works . But due to the age of the answer (and unity build), I had to do some update tweaks
Below is my hack:
renderer.material.color = Color.Lerp(Color.red, Color.black, t);
Obviously the color.red etc are examples only.
Sharing is Caring https://twitter.com/IndieNendoroid
What do you mean by
? The code still works the same. Also i don't see what "tweak" you have used in your case. You do exactly the same as robert. $$anonymous$$aybe you haven't realised that the code is written in UnityScript and not in C#?due to the age of the answer (and unity build)