Going From Flash ActionScript 3 to ActionScript 2

by

REASON

We are teaching AS3 to this year’s Sheridan Interactive Multimedia and some students have not seen AS2. We want the students to be somewhat aware of AS2 so if they see AS2 in the workplace they will have an idea of what is going on. Our mobile prototypes will be coded in Flash Lite 3 which is also AS2 based.

So this is an unusual situation. Most literature on the Web talks about how to convert or go from AS2 to AS3. In general, this can be turned around to retrograde from AS3 to AS2 but it is a little annoying to read if you have not done any AS2 and only know AS3. It is difficult because the writing assumes that you know AS2.

This post is to help those who know AS3 to write code in AS2. It is certainly not exhaustive as there were about 800 changes to the language. See:
http://livedocs.adobe.com/flex/201/langref/migration.html

It should be noted that we absolutely love AS3 and would not for a second want to return to AS2. AS3 has been so much easier to teach because of its consistency. It is more organized, flexible, powerful and fast. There is an initial organization set up. But once you are over that, it is almost redundant in its usage. For a chart overview of AS3 organization, please see:
http://www.flickr.com/photos/danzen/1382459629/

ORGANIZATION

You can choose to make an AS2 Flash file and when you do the code window shows AS2 and AS1 code in the left hand reference area. This is organized differently than all the nicely organized packages in AS3. Most of the classes you will want to look at are under ActionScript 2 Classes > Core or Movie. Movie is a hodgepodge of classes specific to Flash like MovieClip, TextField, etc. So that will look somewhat familiar.

Most coders coded on the timeline in a single timeline script on the first frame of the Movie. Sit on the first frame and press F9 to see the code window. You do not need to declare packages or start a class – you just code with variables and functions.

Advanced coders imported classes from external AS files. These could be in a package although there is no package block in the external AS itself – you put the package name at the front of the class name: class package.ClassName { You can then make a class approximately the same way as AS3 in the external AS file. If you wanted to make a MovieClip call a class when an instance of the MovieClip is created, you would set the linkage on the MovieClip to export for ActionScript and then set the Class to the external AS file. Slightly different than AS3.

People who were used to AS1 coding sometimes put code out on buttons and on MovieClips. We will not address that code – but watch out for it if you can’t seem to find any code in a legacy project.

BASIC DIFFERENCES

  • There is no Sprite class in AS2 we used the MovieClip class instead.
  • There are a number of properties of MovieClips and TextFields that started with _. Here are the most used ones in AS2 I am sure you will recognize the translation. Just look through properties of a MovieClip in AS2 to spot these:
    • _x, _y, _alpha, _visible, _width, _height, _xscale, _yscale
  • In AS3 we use a value from 0 to 1 for a various properties. In AS2 these are usually from 0 to 100. For instance:
    • myClip.alpha = .7 in AS3 is myClip._alpha = 70 in AS2
  • Instead of stage to reference the root timeline we used _root to reference the root timeline. If you are embedding a swf into another swf that other swf becomes the _root unless in the swf you are embedding you write _lockroot = true.
  • There is no addChild() – we used the _visible property.
  • Flash had _level for depth management so look up myClip.swapDepths(otherClip) and myClip.swapDepths(myClip.getNextHighestDepth()) – yum.

MOVIECLIP & TEXTFIELD DIFFERENCES

  • You did not instantiate the MovieClip class like new MovieClip(). Instead you had these methods available:
    • holderClip.createEmptyMovieClip(“name”, depth); // you figure out the depth.
    • holderClip.duplicateMovieClip(“name”, depth); // makes a copy (want in AS3)
    • holderClip.attachMovie(“linkageName”, “name”, depth); // from the library
    • And similarly, you did not instantiate a TextField like new TextField – instead:
    • holderClip.createTextField(“name”, depth, x, y, width, height);

EVENT DIFFERENCES

  • Common events were handled with a function literal

myButton.onRelease = function() { // note there is no click event
trace (“hi”);
trace (this); // will give you reference to myButton
}

  • Then there is the addListener() method:

myListener = new Object();
myListener.onKeyDown = function() {

if (Key.getCode() == 39) {
trace (“right arrow”);
}
}
Key.addListener(myListener);

  • And the addEventListener() method for components and custom events:

var myListener = new Object();
myListener.someEvent = function() {
trace (“event captured”);
}
myObject.addEventListener(“someEvent”, myListener);

  • And you would dispatch an event by adding the following code to your class

private var dispatchEvent:Function;
public var addEventListener:Function;
public var removeEventListener:Function;

  • And in your constructor:

mx.events.EventDispatcher.initialize(this);

  • And finally where you want to dispatch the event:

this.dispatchEvent({type:”someEvent”, target:this, param:”value”});

MISSING AND CHANGED CLASSES

There are many classes that you do not have – it is easy enough to figure out what they are – they will not be there ;-). But in some cases there are substitutes. Such as:

  • Timer() -> use setInterval() function like so:

clearInterval(myID);
myID = setInterval(myFunction, 1000, parameter);
// or in a class
myID = setInterval(this, “myMethod”, 1000, parameter);
// scope gets all mixed up – it’s a pain

  • You have none of the .net classes for passing data instead use LoadVars:

myVars = new LoadVars();
myVars.id = 12345;
newVars = new LoadVars();
newVars.onLoad = loaded;
// or if in a class
newVars.onLoad = mx.utils.Delegate.create(this, loaded);
myVars.sendAndLoad(“serverscript”, newVars, “POST”);

private function loaded() {
answer = newVars.answer;
}

  • XML class is completely different – it is not E4X. To access nodes it is something like this:

// if you read in XML you will want to set the:
myXML.ignoreWhite = true;
myXML.childNode[0].childNodes gives you access to the nodes under the root node
// then you can use properties like so:
myXML.childNode[0].childNodes[0].nodeName // gives node name
myXML.childNode[0].childNodes[0].attributes.age // gives value of age attribute
myXML.childNode[0].childNodes[0].nodeValue // gives value of node

COMPONENT DIFFERENCES

Well, there are probably a number of differences here but obvious ones are availability. In AS2 there were more components so check out the component panel to find:

  • AS2 – Tree – XML data made into a directory tree
  • AS2 – Accordion – bars to click on to reveal content between
  • AS2 – Menu and Menu Bar – for drop down menus
  • AS2 – A bunch of data components for connecting to datasets, XML and webservices
  • No Slider or TileList in AS2.

CONCLUSION

This has been an interesting trip through memory lane. Once again, we love AS3 and do not want to go back. Thank you Adobe for continuing to make improvements.

Dan Zen

Advertisements

Tags: , , , , , , , , , , ,

15 Responses to “Going From Flash ActionScript 3 to ActionScript 2”

  1. Adrian Says:

    Finding this post VERY helpful to refer to, Dan. Thanks!

  2. Cat Says:

    Hi! Great post, and very useful. I have been learnnig AS3 over the past 6 months and have started to now look at AS2 as it seems more widely used…Could do with more helpful posts like this on the web! 🙂

  3. Vikky Says:

    Interesting but not clear on what you are telling!!
    Be specific like for this in AS2.0 and same in AS3.0
    That would help starters…
    Simply writing bullet points wont help any one…

    Cheers

  4. Dan Zen Says:

    Hi Vikky, thank you for your comment on the AS2 – AS3.

    With respect to being specific… I was specific with respect to the differences but not detailed in how to do each of the differences. How to actually do each of these things can be found in books, tutorials, help files, etc. and is beyond the scope of the article.

    Having said that, if you have any specific questions, let me know.

  5. Ronnie Says:

    Can anyone paste how this AS3 Action would look like on AS2?

    // hide processing mc
    processing_mc.visible=false;
    // Combo Box I create to populate Countries
    function addCountriesToList():void{
    CountryList.addItem({label:”United States”});
    CountryList.addItem({label:”Canada”});
    CountryList.addItem({label:”Mexico”});
    }
    // Run Function Above Now
    addCountriesToList():

    var variables:URLVariables= new URLVariables;

    // Build the VarSend Variable
    var varSend:URLRequest=new URLRequest(“form_parse.php”);
    varSend.method=URLRequestMethod.POST;
    varSend.data=variables;

    //Build the varLoader Variable
    var varLoader:URLLoader=new URLLoader;
    varloader.dataFormat=URLLoaderDataFormat.VARIABLES ;
    varloader.addEventListener(Event.COMPLETE, completeHandler);

    // Handler for the PHP Completion and return of Message Status
    function completeHandler(event.Event):void{
    // Remove processing clip
    processing_mc.visible=false;
    name_txt.text=””;
    email_txt.text=””;

    // Load the Response from PHP Here
    status_txt.text=event.target.data.return_msg;
    }

    // Add Event Listener for Submit button click
    submit_btn.addEventListener(MouseEvent.CLICK, ValidateAndSend);

    //function ValidateAndSend
    function ValidateAndSend(event:MouseEvent):void{
    // Validate Fields
    if(!name_txt.lenght){
    status_txt.text=”Please enter your Name”;
    }else if (!email_txt.lenght){
    status_txt.text=”Please enter your Email”;
    }else if (!country_list.lenght){
    status_txt.text=”Please select your Country”;
    }else if (!state_list.lenght){
    status_txt.text=”Please select your State”;
    }else if (!city_list.lenght){
    status_txt.text=”Please select your city”;
    }else{

    //All is good send the Data to PHP now
    processing_mc.visible=true;

    //Ready the variables in my form for sending
    variables.userName=name_txt.text;
    variables.userEmail=email_txt.text;
    variables.userCountry=country_list.value;
    variables.userState=state_list.value;
    variables.userCity=city_list.value;
    variables.userRadiobutton=radiobutton.value;

    //Send the Data to PHP now
    varLoader.load(varSend);

    }// Close else condition for Error Handling

    ]//Close and Validate Function

  6. Dan Zen Says:

    I don’t have time to do it all… but here are some aspects:

    use _visible rather than visible.

    The component will work roughly the same way I think – use an older component though.

    Your error checking would be the same I think.

    For the sending and receiving of variables you would do it in two steps. Prepare your variables and send. Then set up an event to receive and receive your variables in the event. So roughly how you have it here but use the following syntax:

    // set up object to send variables
    myVars = new LoadVars();
    myVars.score = 234;
    myVars.player = “Dan Zen”;

    //set up object to receive variables
    newVars = new LoadVars();
    newVars.onLoad = showHighscore;

    myButton.onRelease = function () {
    myVars.sendAndLoad(“game3.php”, newVars, “POST”);
    }

    function showHighscore() {
    message.text = newVars.bestPlayer + ” has the high score of ” + newVars.bestScore
    }

  7. Ronnie Padron Says:

    Hey Dan,

    Thank you so much for your help. I was able to get it together and it is working!

    Now i need to figure out how to add a Browse button on my AS2 form so users can send Word files using my PHP file which will then send me an e-mail with the information entered on the form plus their file.

    Do you think you could help me out?

    This is my script.

    // hide processing mc
    processing_mc._visible=false;
    // Combo Box I create to populate Countries
    function addCountriesToList() {
    country_list.addItem({label:”United States of America”});
    }

    // Run Function Above Now
    addCountriesToList();

    var variables:LoadVars=new LoadVars();
    var receiver_lv:LoadVars=new LoadVars();

    var varSend=”form_parse.php”;
    var varSend_method=”POST”;

    //Build the varLoader Variable
    receiver_lv.onLoad=completeHandler;

    // Handler for the PHP Completion and return of Message Status
    function completeHandler() {
    // Remove processing clip
    processing_mc._visible=false;
    name_txt.text=””;
    email_txt.text=””;
    state_txt.text=””;
    city_txt.text=””;

    // Load the Response from PHP Here
    status_txt.text=this.return_msg;
    }

    // Add Event Listener for Submit button click
    submit_btn.onRelease=ValidateAndSend;

    //function ValidateAndSend
    function ValidateAndSend() {
    // Validate Fields
    if (!name_txt.length) {
    status_txt.text=”Please enter your Name”;
    } else if (!email_txt.length) {
    status_txt.text=”Please enter your Email”;
    } else if (!country_list.length) {
    status_txt.text=”Please select your Country”;
    } else if (!state_txt.length) {
    status_txt.text=”Please enter your State”;
    } else if (!city_txt.length) {
    status_txt.text=”Please enter your city”;
    } else {

    //All is good send the Data to PHP now
    processing_mc._visible=true;

    //Ready the variables in my form for sending
    variables.userName=name_txt.text;
    variables.userEmail=email_txt.text;
    variables.userCountry=country_list.value;
    variables.userState=state_txt.text;
    variables.userCity=city_txt.text;

    //Send the Data to PHP now
    variables.sendAndLoad(varSend,receiver_1v,varSend_method);

    }// Close else condition for Error Handling

    }//Close and Validate Function

    And this is my PHP File

    Thank you!!!!

  8. Ronnie Padron Says:

    And this is my PHP File

    Thank you!!!!

  9. Stephan Says:

    someone can conver this AS3 class in AS2 please…

    Very thanks in advance…Stephan

    package org.Captcha
    {
    import flash.display.*;
    import flash.events.*;
    import flash.geom.*;
    import flash.text.*;

    public class Captcha extends MovieClip
    {
    private var clip_mc:MovieClip;

    private var captcha_array:Array;

    private const CAPTCHA_LENGTH:int=8;

    private var captcha:String=””;

    public function Captcha()
    {
    addEventListener(Event.ADDED_TO_STAGE,init);
    }

    private function init(evt:Event):void
    {
    removeEventListener(Event.ADDED_TO_STAGE,init);

    captcha_array=new Array(“A”,”B”,”C”,”D”,”E”,”F”,”G”,”H”,”I”,”J”,”K”,”L”,”M”,”N”,”O”,”P”,”Q”,”R”,”S”,”T”,”U”,”V”,”W”,”X”,”Y”,”Z”,”a”,”b”,”c”,”d”,”e”,”f”,”g”,”h”,”i”,”j”,
    “k”,”l”,”m”,”n”,”o”,”p”,”q”,”r”,”s”,”t”,”u”,”v”,”w”,”x”,”y”,”z”,”0″,”1″,”2″,”3″,”4″,”5″,”6″,”7″,”8″,”9″);

    createClip();
    createBackground();
    createCaptcha();
    createText();
    }

    private function createClip():void
    {
    clip_mc=new MovieClip();
    addChild(clip_mc);
    }

    private function createBackground():void
    {
    var fillType:String=GradientType.LINEAR;
    var colors:Array=[Math.random()*0xFFFFFF,Math.random()*0xFFFFFF];
    var alphas:Array=[1,1];
    var ratios:Array=[0x00,0xFF];
    var matr:Matrix=new Matrix();
    matr.createGradientBox(20,20,0,0,0);
    var spreadMethod:String=SpreadMethod.REFLECT;
    clip_mc.graphics.beginGradientFill(fillType,colors,alphas,ratios,matr,spreadMethod);
    clip_mc.graphics.drawRect(0,0,140,40);
    }

    private function createCaptcha():void
    {
    for(var i:int=0;i < CAPTCHA_LENGTH;i++)
    {
    var randomNumber:int=Math.floor(Math.random()*captcha_array.length);
    captcha+=captcha_array[randomNumber];
    }
    }

    private function createText():void
    {
    var field_txt:TextField=new TextField();
    field_txt.multiline=false;
    field_txt.selectable=false;
    field_txt.embedFonts=true;
    field_txt.defaultTextFormat=getFormat();
    field_txt.text=captcha;
    field_txt.width=field_txt.textWidth+5;
    field_txt.height=field_txt.textHeight;
    field_txt.x=(clip_mc.width-field_txt.textWidth)/2;
    field_txt.y=(clip_mc.height-field_txt.textHeight)/2;
    clip_mc.addChild(field_txt);
    }

    private function getFormat():TextFormat
    {
    var format:TextFormat=new TextFormat();
    format.font="Flubber";
    format.size=24;
    format.color=0xFFFFFF;

    return format;
    }

    public function checkCaptcha(str:String):Boolean
    {
    if(str===captcha)
    return true;
    else
    return false;
    }
    }
    }

  10. hermanwhyd Says:

    thanks you,,,
    i like your this tutorial,,,

  11. Richard Johnn » Going back from Actionscript 3 to Actionscript 2 Says:

    […] Going from Flash Actionscript 3 to Actionscript 2 […]

  12. Joao paulo machado Says:

    Boas,
    Gostaria de saber se me podem ajudar.
    A minha nota final depende deste problema.
    Tenho que passar este codigo que esta em 3.0 para o actionscript 2.0.

    import flash.display.Bitmap;
    import flash.display.BitmapData;

    var cam:Camera = Camera.getCamera();
    var video:Video = new Video(320,240);
    video.attachCamera(cam);
    video.x = 20;
    video.y = 20;
    addChild(video);

    var bitmapData:BitmapData = new BitmapData(video.width,video.height);

    var bitmap:Bitmap = new Bitmap(bitmapData);
    bitmap.x = 360;
    bitmap.y = 20;
    addChild(bitmap);

    capture_mc.buttonMode = true;
    capture_mc.addEventListener(MouseEvent.CLICK,captureImage);

    function captureImage(e:MouseEvent):void {
    bitmapData.draw(video);
    }

    Agradeço resposta. Abraço

  13. Dan Zen Says:

    Sorry – just noticed these questions… I guess AS2 is pretty far in the past for me so I hope you found answers – I just don’t have time to go through the questions. Hope you understand… thanks.

  14. tweetdimitra Says:

    Someone can help me conver this AS3 in AS2 please??!!!

    package {
    import flash.display.*;
    import flash.events.*;
    import flash.ui.*;

    public class Memory extends MovieClip
    {
    private var score, life:Number;
    private var doLoseLife, gotoWin, gotoLose:Boolean;
    private var firstCard, secondCard:Card;
    private var cardValues, cards:Array;

    public function Memory()
    {

    }

    //All Start Functions
    public function startMenu()
    {
    stop();
    btnStartGame.addEventListener(MouseEvent.CLICK, gotoStartGame);
    btnHowToPlay.addEventListener(MouseEvent.CLICK, gotoHowToPlay);
    }

    public function startHowToPlay()
    {
    btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
    }

    public function startWin()
    {
    btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
    }

    public function startLose()
    {
    btnBack.addEventListener(MouseEvent.CLICK, gotoMenu);
    }

    public function startGame()
    {
    score = 0;
    life = 10;
    doLoseLife = false;
    gotoWin = false;
    gotoLose = false;
    firstCard = null;
    secondCard = null;
    cards = new Array();

    setupGame();

    //Shuffle
    cardValues = new Array(“card1″,”card1″,”card2″,”card2″,”card3″,”card3″,”card4″,”card4”,
    “card5″,”card5″,”card6″,”card6″,”card7″,”card7”);
    for (var i=0; i<100; i++)
    {
    var swap1 = Math.floor(Math.random()*14);
    var swap2 = Math.floor(Math.random()*14);

    var tempValue = cardValues[swap1];
    cardValues[swap1] = cardValues[swap2];
    cardValues[swap2] = tempValue;
    }

    //Deal
    for (var i=0; i<14; i++)
    {
    cards[i].hiddenValue = cardValues[i];
    cards[i].addEventListener(MouseEvent.CLICK, flipCard);
    }

    addEventListener(Event.ENTER_FRAME,update);

    stage.focus = this;
    }

    public function startLevel2()
    {
    life = 10;
    doLoseLife = false;
    gotoWin = false;
    gotoLose = false;
    firstCard = null;
    secondCard = null;
    cards = new Array();

    setupGame();

    //Shuffle
    cardValues = new Array("card1","card1","card2","card2","card3","card3","card4","card4",
    "card5","card5","card6","card6","card7","card7","card8","card8");
    for (var i=0; i<100; i++)
    {
    var swap1 = Math.floor(Math.random()*14);
    var swap2 = Math.floor(Math.random()*14);

    var tempValue = cardValues[swap1];
    cardValues[swap1] = cardValues[swap2];
    cardValues[swap2] = tempValue;
    }

    //Deal
    for (var i=0; i<16; i++)
    {
    cards[i].hiddenValue = cardValues[i];
    cards[i].addEventListener(MouseEvent.CLICK, flipCard);
    }

    addEventListener(Event.ENTER_FRAME,update);

    stage.focus = this;
    }

    private function setupGame()
    {
    //Check the classes of the movieclips and push them into the
    //appropriate arrays
    for (var i=0; i= 70)
    {
    gotoAndStop(“level2”)
    }
    }
    else if (currentLabel == “level2”)
    {
    if (score >= 150)
    {
    gotoWin = true;
    }
    }

    if (life <= 0)
    {
    gotoLose = true;
    }
    }

    private function handleDraw()
    {
    //Handle display
    txtScoreP1.text = String(score);
    txtLife.text = String(life);
    }

    private function triggerGoToWin()
    {
    removeEventListener(Event.ENTER_FRAME, update);
    gotoAndStop("win");
    }

    private function triggerGoToLose()
    {
    removeEventListener(Event.ENTER_FRAME, update);
    gotoAndStop("lose");
    }

    //Misc Functions
    private function resetGame()
    {
    for (var i in cards)
    cards[i].gotoAndStop("back");
    }

    }//end class
    }//end package

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: