Wolfsurge
Wolfsurge

Reputation: 37

How can I reverse an easing function?

So, I have an easing function (stored as a lambda), that takes a factor from between 0 and 1, and eases it accordingly. This is the cubic-out easing.

{ input -> 1 - (1 - input).pow(3.0) }

In my animation class, when getting the value, if the animation is currently expanding, it simply eases the value, but when contracting, it minuses the value from 1 before easing it:

easing.ease(1f - factor)

What I want to do is to reverse the easing - like these two images (x represents the factor, t represents the time):
Expanding: expanding

Contracting: contracting

The full animation class can be found here, with the easings enum class in the same package. The easing happens in the getAnimationFactor function, and I know that there's a useless if statement, I accidentally pushed it.

Thanks in advance.

Upvotes: 0

Views: 560

Answers (1)

gidds
gidds

Reputation: 18627

While there are programmatic ways to find the inverse of an arbitrary (monotonic) function, they're not simple or efficient. (I think you'd have to use a progressive approximation loop, which would be much slower and/or much less accurate.)

But you know the function! So you can use mathematical techniques to determine the inverse function, and then implement that in Kotlin.

For your first case:
            t = 1 - (1 - x)³
You can manipulate* that to give:
            x = 1 - ∛(1 - t)

…which could be implemented in Kotlin as:
            { 1 - (1 - it).pow(1.0/3) }

(The second case is left as an exercise for the reader :-)


(* The algebra is very straightforward, but I'll spell it all out here for those who aren't familiar with it:
            t = 1 - (1 - x)³
Subtract 1 from each side:
            t - 1 = - (1 - x)³
Multiply each side by -1:
            1 - t = (1 - x)³
Take the cube root of each side:
            ∛(1 - t) = 1 - x
Subtract 1 from each side:
            ∛(1 - t) - 1 = - x
Multiply each side by -1:
            1 - ∛(1 - t) = x
And switch sides:
            x = 1 - ∛(1 - t)
QED∎

The only step needing further explanation is taking the cube root of each side, which is OK here because every real number has exactly one real cube root — we're ignoring the complex ones! If it were a square root, or any other even-numbered root, if would only work for non-negative reals.)

Upvotes: 0

Related Questions