August 31, 2009

ActionScript 3: Get the percentage of a value within a number range

Sometimes, when creating UI elements or performing geometric calculations based on the sizes or positions of objects (or lots of other tasks), it's useful to find the percentage of a number within a range of 2 other numbers. Use this function to easily relate these values:

/**
* Returns a percentage of a value in between 2 other numbers.
* @param bottomRange low end of the range.
* @param topRange top end of the range.
* @param valueInRange value to find a range percentage of.
* @return The percentage of valueInRange in the range.
* @use getPercentWithinRange( 50, 150, 100 ); // displays 50
*/
public static function getPercentWithinRange( bottomRange:Number, topRange:Number, valueInRange:Number ):Number
{
// normalize values to work off zero
if( bottomRange < 0 )
{
var addToAll:Number = Math.abs( bottomRange );
bottomRange += addToAll;
topRange += addToAll;
valueInRange += addToAll;
}
else if( bottomRange > 0 )
{
var subFromAll:Number = Math.abs( bottomRange );
bottomRange -= subFromAll;
topRange -= subFromAll;
valueInRange -= subFromAll;
}
// simple calc to get percentage
return 100 * ( valueInRange / ( topRange - bottomRange ) );
}

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.