Hi!
I have been trying to make an InOutQuad value progression. It’s to modify velocity of a Rigidbody going from -1 to 1, and then backwards. I have been looking for a function and found this two:
private static float InOut(float k)
{
if ((k *= 2f) < 1f) return 0.5f * k * k * k;
return 0.5f * ((k -= 2f) * k * k + 2f);
}
public static float EaseInOutQuad(float start, float end, float value)
{
value /= .5f;
end -= start;
if (value < 1) return end * 0.5f * value * value + start;
value--;
return -end * 0.5f * (value * (value - 2) - 1) + start;
}
“Easings” are applied to linear interpolations. The value they take is usually a percentage. Does this make any sense?
using System.Collections;
using UnityEngine;
public class Junk : MonoBehaviour
{
IEnumerator Fubar()
{
bool inverted = false;
float[] someVars = new float[2];
while (true)
{
//This bit is to make sure it goes back and forth
inverted = !inverted;
someVars[0] = inverted ? 1 : -1;
someVars[1] = inverted ? -1 : 1;
//The var that's going to be the result of our interpolation. This could be an axis of our rigidbody's velocity.
float iCanBeAnything = 0f;
//What time is it as we're starting this?
float timeStamp = Time.time;
//How long is this going to take?
float duration = 1f;
//Yay, we're running until our duration is over. Let's change the world.
while (Time.time < timeStamp + duration)
{
//What is the percentage of our interpolation currently completed????
float t = (Time.time - timeStamp) / duration;
//Pass the normalized time variable(our percentage) through our easing method so we can get our relative value
t = QuadraticEaseInOut(t);
//Let's lerp with our new shiny relative value, rather than the linear percentage of completion.
iCanBeAnything = Mathf.Lerp(someVars[0], someVars[1], t);
//We don't like stack overflows
yield return null;
}
//Adjust the variable with its final value. The lower our FPS, the more apparent the gap between
//the last iteration of the while loop and the final value is. Let's correct it by assigning our value.
iCanBeAnything = someVars[1];
}
}
float QuadraticEaseInOut(float p)
{
if (p < 0.5f)
return 2 * p * p;
return (-2 * p * p) + (4 * p) - 1;
}
}
YEAH! It make all the sense. Thanks for the help.
I’m starting to learn about easings and it was driving me crazy. So, does it coroutine works with any other easing? I soupose, by how it runs.
Yeah sure, just pass the t variable into whatever easing you want. Just remember that you’ll need to use an unclamped LERP if you use easings that are expanding beyond the 0-1 range.
e.g. Let’s say you want to generate a sine wave and you want your wave to do 2 complete cycles, you could do this
//Get the percentage of completion
float t = (Time.time - timeStamp) / duration;
//Ease it
t = Mathf.Sin(Mathf.PI * t * 4f);
float waveAmplitude = 52f;
float myEasedVariable = Mathf.LerpUnclamped(0f, waveAmplitude, t);