Friday, July 25, 2008

Tweener and onEnterFrame

Today I figured out how to use Tweener and onEnterFrame together to create tweens of dynamically drawn content. This allows you to easily change the nature of the tween via the transition equation.

Like this (three transition equations shown here):

The code:
 public function animateLine(e:MouseEvent){   
   var easeType:String = e.target.label;
   addEventListener(Event.ENTER_FRAME, drawLine);
   lineLength = 0;
   //the ease outs work much better here
   Tweener.addTween(  this, 
                      {  lineLength:stage.stageWidth, 
                         time:2, transition:easeType, 
                         onComplete:this.removeEventListener, 
                         onCompleteParams:[Event.ENTER_FRAME, drawLine]
                      }
                   );
  }
  
  public function drawLine(e:Event){
   line.graphics.clear();
   line.graphics.lineStyle(0, 0xff0000);
   line.graphics.lineTo(lineLength, 0);
   line.x = (stage.stageWidth - line.width)/2;
  }
(Sorry about the formatting, I'm still working on that.)

The animateLine function first sets up an enterFrame event listener. This event listener (drawLine) will redraw a line each time it is called using the variable lineLength for the length of the line.

Next we use Tweener.addTween to update the value of lineLength. So the value of lineLength is now changing based on a transition equation over time. Tweener.addTween also allows you to set a callback function (and the arguments). So I used this feature to call the removeEventListener function when lineLength has finished tweening.

Click here to download full source.