Easy Quadratic Ease In/Out Algorithm
Recently I wanted to add an ease in / out effect to an animation that I was writing. I searched the internet, but couldn't find anything particularly useful that actually explained how the algorithm worked, so I am writing this post.
The formula I ended up using works by taking an input between 0 and 1, and spitting out an adjusted output which is also between 0 and 1, but has the easing function applied. For easing both in and out, there are two formulae.
To ease in, for $y < 0.5$: $$ y = 2x^2 $$
To ease out, for $y >= 0.5$: $$ y = -1 + x(4 - 2x) $$
If you want to only ease in or ease out, go ahead and use just one of the above equations, and forget about the other one. Or, you can combine them to ease in and out at the same time.
Initially, I wrote my implementation in C♯ while I was testing the equations. Here's what I came up with:
using System;
using System.Threading;
namespace EasingTest
{
class MainClass
{
static int width = 75;
static int frameDelay;
public static float QuadEaseInOut(float time)
{
return time < 0.5f ? 2.0f * time * time : -1.0f + (4.0f - 2.0f * time) * time;
//return t<.5 ? 2*t*t : -1+(4-2*t)*t
}
public static void displayEase(float time)
{
float ease = QuadEaseInOut(time);
int nextWidth = (int)(ease * width);
Console.Write("{0}{2}{1}\r", new string(' ', nextWidth), new String(' ', width - nextWidth), 'o');
}
public static void Main(string[] args)
{
Console.Write("Enter the frame delay: ");
frameDelay = int.Parse(Console.ReadLine());
int count = 0;
float step = 0.01f;
bool dir = false; // false = right->left, true = left->right
while(count < 10)
{
if(!dir)
{
for(float t = step; t < 1; t += step)
{
displayEase(t);
Thread.Sleep(frameDelay);
}
dir = true;
}
else
{
for(float t = 1; t > 0; t -= step)
{
displayEase(t);
Thread.Sleep(frameDelay);
}
dir = false;
}
count++;
}
}
}
}
Here's an example run of the above code:
The important stuff happens in the QuadEaseInOut function on line #11. If you just want the easing function, here it is in multiple languages:
C Sharp
public static float QuadEaseInOut(float time)
{
return time < 0.5f ? 2.0f * time * time : -1.0f + (4.0f - 2.0f * time) * time;
}
Javascript
function (t)
{
return t<.5 ? 2*t*t : -1+(4-2*t)*t;
}
The above can easily be ported to other languages if you aren't using C♯ or Javascript.
Sources
I originally got this algorithm from gre's wonderful gist, which also contains a number of other easing functions that you might be interested in.