This blog has moved to a new location! http://iqandreas.github.com/

Thursday, August 13, 2009

TIP: Tweening Functions

I often get annoyed by the fact that most tweening engines do not allow the tweening of functions.

Here is how you work around that!

This example will be using TweenLite, but if anyone wants me to write similar code for other Tweening engines (such as GTween or Tweener), just ask.


Here I will be tweening the graphics.lineTo() function to draw a simple line from the top left corner of the stage down to the bottom right, straight through the center of the movie, but tweened!

The key is creating a new object, and then applying the needed properties of that object to the function you want to run.

ActionScript Code:
import gs.TweenLite;

//This sprite is what we will draw the lines on, insead of drawing them directly onto the stage.
var lineSprite:Sprite = new Sprite();
this.addChild(lineSprite);

//The key is to create a new object, and put tweenable properties on it
var drawObj:Object = new Object();
drawObj.targetObject = lineSprite;
drawObj.x = 0;
drawObj.y = 0;
drawObj.endX = this.stage.stageWidth;
drawObj.endY = this.stage.stageHeight;

TweenLite.to(drawObj, 5, { x:drawObj.endX, y:drawObj.endY,
onStart:startDraw, onStartParams:[drawObj],
onUpdate:updateDraw, onUpdateParams:[drawObj] } );

function startDraw(obj:Object):void
{
obj.targetObject.graphics.lineStyle(5, 0x000000);
obj.targetObject.graphics.moveTo(obj.x, obj.y);
}

function updateDraw(obj:Object):void
{
//Here is where all the action happens.
//This code is executed each and every time the tweening engine changes the value of x or y
//Here is where you place the function you want to tween, and use whatever parameters are needed
obj.targetObject.graphics.lineTo(obj.x, obj.y);
}



That code can also be abbreviated down a lot. This code is less clear to read, but will run faster. Also, instead of creating a new function that will call the function to be tweened, the lineTo() function will be called directly.
ActionScript Code:
import gs.TweenLite;

//This sprite is what we will draw the lines on, insead of drawing them directly onto the stage.
var lineSprite:Sprite = new Sprite();
this.addChild(lineSprite);

//The key is to create a new object, and put tweenable properties on it
var drawObj:Object = {targetObject:lineSprite, x:0, y:0, endX:this.stage.stageWidth, endY:this.stage.stageHeight};

//Prepare the sprite for drawing
//This code was originally in a startDraw function
drawObj.targetObject.graphics.lineStyle(5, 0x000000);
drawObj.targetObject.graphics.moveTo(obj.x, obj.y);

TweenLite.to(drawObj, 5, { x:drawObj.endX, y:drawObj.endY,
onUpdate:obj.targetObject.graphics.lineTo,
onUpdateParams:[drawObj.x, drawObj.y]