Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute easing duration as a function of distance

Tags:

javascript

I'd like some function to compute the duration for an animation such that even when the distance changes, the speed remains constant.

====================================
|                                  |
|<============ width =============>|
|                                  |
|         <====== distance1 ======>|
|                                  |
|               <=== distance2 ===>|
|                                  |
===================================

This is trivial to accomplish when dealing with linear easing,

function getDuration (width, distance, duration) {
  return duration * (1 - distance / width);
}

However, this becomes much more complex when using non-linear easing functions, such as easeInOutQuad (An illustration of this problem: http://jsfiddle.net/Wexcode/rdrbm8et/3/).

Given an easing function, such as easeInOutQuad, how do I compute the duration such that the speed for any distance remains constant?

easeInOutQuad: function (t) { return t<.5 ? 2*t*t : -1+(4-2*t)*t },

Source: https://gist.github.com/gre/1650294

easeInOutQuad

Source: http://api.jqueryui.com/easings/

like image 592
Wex Avatar asked Sep 02 '15 14:09

Wex


1 Answers

Given a function y = f(t), where y is the distance and t is the time simply solve for t, and use the t = g(y) function to determine how long it takes to get to a given distance.

For instance, in the easeInOutQuad easing, -1+(4-2*t)*t can be solved:

Solved equation

Source: http://www.wolframalpha.com/input/?i=Solve%28y+%3D+-1%2B%284-2*t%29*t%2C+t%29

In practice, you would multiply t times your duration to get your new duration.

 var ratio = distance / width;
 if (ratio <= .5) {
   return duration * Math.sqrt(ratio * 1/2);
 } else if (ratio <= 1) { 
   return duration * (1 - Math.sqrt(1-ratio) / Math.sqrt(2));
 }

http://jsfiddle.net/Wexcode/rdrbm8et/6/

like image 116
Wex Avatar answered Sep 30 '22 06:09

Wex