Wednesday 22 May 2013

Easing/Tweening

So a useful tool for game development is a technique called "easing" or "tweening". This is often used for skeletal animation, but is also useful for other tasks. Basically what it involves is updating a value between a start and end point over time. So for example if I wanted to move a sprite across the screen along the x axis starting at x = 200 and ending at x = 1000 for a duration of 1.5 seconds, then the x position of the sprite could be tweened between these two values.

Below I will show you four quadratic easing functions (language is C#, but you can adapt these functions to whatever language you are using):

All the functions will have the same parameters:
currentTime: this is the current time of the tween
start: this is the start value of the tween
diff: this is the difference between the end and start value
length: this is the total time of the tween

Linear (the value will be changed at a constant rate):



public float Linear(float currentTime, float start, float diff, float length)
{
     return diff * currentTime / length + start;
}



Ease Out (the value will change quickly at first and then slow down)



















public float EaseOut(float currentTime, float start, float diff, float length)
{
      currentTime /= length;
      return -diff * currentTime*(currentTime-2) + start;
}



Ease In (the value will change slowly at first and then speed up)




















public float EaseIn(float currentTime, float start, float diff, float length)
{
     currentTime /= length;
     return diff*currentTime*currentTime + start;
}



Ease In Ease Out(the value will change slowly at the beginning and end, and change quickly in the middle)





















public float EaseInOut(float currentTime, float start, float diff, float length)
{
     if ((currentTime /= length / 2) < 1)
     {
         return diff / 2 * currentTime * currentTime + start;
     }

     return -diff / 2 * ((--currentTime) * (currentTime - 2) - 1) + start;
}


Example:
So let's use the example from above. We want to move a sprite along the x axis between x = 200 and x =  1000 for a duration of 1.5 seconds. We would set up the parameters like this:

currentTime: you'd need to set up a timer for the tween and update it using your game engine/framework's delta time (time between last frame and current frame)
start: in this case 200
diff: in this case 1000 - 200 = 800
length: in this case 1.5

so call this line every frame:
spriteX = Linear(timer, 200, 800, 1.5);


No comments:

Post a Comment