Chapter 17 Example 12

by actionscriptbible
♥0 | Line 65 | Modified 2009-06-29 14:53:43 | MIT License
play

ActionScript3 source code

/**
 * Copyright actionscriptbible ( http://wonderfl.net/user/actionscriptbible )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/oJPy
 */

package {
  import flash.display.Sprite;
  import flash.events.MouseEvent;
  import flash.geom.Rectangle;
  import flash.text.TextField;
  import flash.text.TextFormat;
  import flash.utils.setTimeout;
  
  public class ch17ex12 extends Sprite {
    protected var letters:Vector.<LetterField> = new Vector.<LetterField>();
    
    public function ch17ex12() {
      var text:String = "Are you watching closely?";
      var sourceTF:TextField = newTF();
      sourceTF.text = text;
      sourceTF.border = true;
      sourceTF.width = sourceTF.textWidth;
      addChild(sourceTF);

      //break it up into letters
      for (var i:int = 0; i < text.length; i++) {
        var lf:LetterField = new LetterField(newTF());
        var letterBounds:Rectangle = sourceTF.getCharBoundaries(i);
        lf.x = letterBounds.x;
        lf.y = letterBounds.y;
        lf.letter = text.charAt(i);
        addChild(lf);
        letters.push(lf);
      }
      
      //remove original
      removeChild(sourceTF);
      stage.addEventListener(MouseEvent.CLICK, startAnimation);
    }
    
    protected function startAnimation(event:MouseEvent):void {
      for (var i:int = 0; i < letters.length; i++) {
        setTimeout(letters[i].startAnimation, i * 30);
      }
    }
    
    protected function newTF():TextField {
      var tf:TextField = new TextField();
      tf.defaultTextFormat = new TextFormat("_serif", 38, 0, false, false);
      tf.selectable = false;
      tf.width = tf.height = 50;
      return tf;
    }
  }
}

import flash.text.TextField;
import flash.display.Sprite;
import flash.events.Event;
class LetterField extends Sprite {
  protected var tf:TextField;
  protected const factor:Number = 1 - 0.08;
  public function LetterField(tf:TextField) {
    this.tf = tf;
    addChild(tf);
  }
  public function set letter(ltr:String):void {
    tf.text = ltr;
    tf.x = -tf.textWidth / 2;
    this.x -= tf.x;
  }
  public function startAnimation():void {
    addEventListener(Event.ENTER_FRAME, tick);
  }
  protected function tick(event:Event):void {
    this.alpha *= factor;
    this.rotationY = 180 * (1-alpha);
  }
}