Saturday, June 12, 2010

Simple Easing

I found a really nice system for easing values over time. I haven't come up with a name for it, though. There's only one catch: in its current state, it only works over fixed time intervals. But there's probably a really simple fix for that.

In a normal code scenario (I'm going to use C) you declare a variable like this:
int variable;
Now, to use this now special "easing" system of variable change, you simply add two more variables to your declaration. The declaration now looks like this:
int variable;
int variableWant;
const int VARIABLE_SPEED = 3;
The first one is the original variable, which I'll call the "actual" value. The second one is the "want" variable, and the third is the "speed" variable. The "want" value is the one you will be changing, while the "actual" value is the one you'll be reading. "Want" is kinda like the "set" variable, while "actual" is the "get" variable. You can use any naming scheme for these variables, but those are the ones I use.

To make this work, you add the following code (which corresponds to the naming scheme above) to a regular-interval function:
variable = (variable * (VARIABLE_SPEED - 1) + variableWant) / VARIABLE_SPEED;
This may look complicated at first, but it's actually really simple. It calculates a new "actual" value based on the "actual" and "want" values by averaging them with specific weight on "actual." If you remember anything about averaging (which you should) you should remember that the last step is to divide by the number of added terms. Well, if you look above, there are (VARIABLE_SPEED - 1) "actual" terms, while there is 1 "want" term. This means that the total number of terms is (VARIABLE_SPEED - 1) + 1, or simply VARIABLE_SPEED, which is what we divide by.

The last variable which hasn't gotten enough attention is VARIABLE_SPEED. This variable's function is simple: it determines the rate at which the ease takes place. If this value is 1, the ease will happen instantly. If the value is 3, the ease will happen rather slow. For a value of 100, you'll be waiting a while.

The only issue with this method of variable change over time is that, theoretically, for values of VARIABLE_SPEED greater than 1, the "actual" value never actually becomes the "want" value. Adding this functionality simply means adding an if statement that sets the "actual" to the "want" for differences less than some constant.

No comments:

Post a Comment