Search code examples
javascriptfunctioncanvastransitioneasing

How to rearrange these easing functions to accept v0, v1 and t?


For example, the easing functions presented in this gist: https://gist.github.com/gre/1650294 would be perfect, but I have no idea how to modify them so that they take v0, v1 and t parameters, like this lerp function I currently have:

_lerp2: function(v0, v1, t) 
{
    return (1 - t) * v0 + t * v1;
}

The easings presented here look good as well: http://gizma.com/easing/ but in this case, I do not understand the "change in value" parameter. Even if I did, I would probably still want those functions like so that they accept only three parameters, v0, v1 and t.

The parameters are as follows: v0 = start value, v1 = end value, t = value between 0 and 1. If, for example, t = 0.5, then lerp returns the average of v0 and v1 for example. I need this same behaviour-ish for these other easing functions somehow.

Or if modifying those easings is too hard, can I somehow modify the existing, working lerp function I have to, say, quadratic easing?


Solution

  • To modify the easing functions from the first page you provided.

    Add the following arguments to all the function definitions.

    eg

    var linear = function (t) { 
        return t 
    };
    

    Becomes

    var linear = function (t, start, end) { 
        return t 
    };
    

    Where start is the the value at time t= 0 and end is the value at t = 1;

    Then in each function remove the return value and assign it to t;

    var linear = function (t, start, end) { 
        return t 
    };
    

    becomes

    var linear = function (t, start, end) { 
        t = t;
        // temp remove return
    };
    

    Then us the new vale of t to lerp between Start and end. This is done by getting the difference between start and end multiplying it by t (which is still in the range 0-1) which scales the range, and then adding start to it to move the new value relative to start.

    var linear = function (t, start, end) { 
        t = t;
        t = (end - start) * t;
        t += start;
        return t;
    };
    
    // can be done in one line
    
    var linear = function (t, start, end) { 
        return (end - start) * t + start;
    };
    
    // or
    var easeOutQuart = function (t) {
        return 1-(--t)*t*t*t 
    }
    
    // becomes
    var easeOutQuart = function (t, start, end) {
        return (end - start) * (1-(--t)*t*t*t) + start ;
    }
    

    Examples

    easeOutQuart(0.5, 10, 20); //  t@0 returns 10 and t@1 returns 20 
    easeOutQuart(0.5, 40, -10); //  t@0 returns 40 and t@1 returns -10 
    easeOutQuart(0.5, -10, 30); //  t@0 returns -10 and t@1 returns 30