August 31, 2009

ActionScript 3: Constant easing function

Sometimes you want to ease a numeric variable or object property to a new value. Typically, you would do this with a tween, via the built-in Tween object, or a 3rd party tween library like Tweener or TweenLite/TweenMax. Sometimes, for a fluid interface, you might want different properties constantly easing (floating) towards their current target destination. In this situation, you would want to interpolate the values incrementally towards the target using the Event.ENTER_FRAME listener. I wrote a nice little function that will take the current value, the target value, and an optional easing value (where higher numbers increase the time to reach the target value), and ease the property towards the target. Check it out:

private function easeTo( current:Number, target:Number, easeFactor:Number = 10 ):Number
{
return current -= ( ( current - target ) / easeFactor );
}

// usage:
this.addEventListener( Event.ENTER_FRAME, onEnterFrameLoop );

private function onEnterFrameLoop( e:Event ):void {
mySprite.x = easeTo( mySprite.x, 200, 5 );
}

Now, wherever mySprite is, it will smoothly tween towards the x destination of 200. This can be applied to any numeric property.

2 comments:

  1. great! but this is the equivalent of the Strong functions. What about Elastic, Bounce, etc?

    I'm looking for the way we can use easeIn, easeOut and easeInOut functions for especial purposes. Can we do that?

    ReplyDelete
  2. I wish I understood the math behind those. This is for cases when you want a value continuously easing towards a target value. I'm not sure how the other cases would translate.

    ReplyDelete