Snippets

Action 3 Example Code and Snippets

admin  

Actionscript 3 is a programming language create by Adobe which was used by Flash. Not so many people know that AS3 was following ActionScript 2 which was a fork of javascript. The interesting fact is that ActionScript 3, was ECMA4 compatible. ECMA is a standard based on which Javascript language is implemented. However, Javascript was not adopting ECMA4, skipping it moving directly to ECMA5 then ECMA6. ActionScript 3 introduced some concepts like strongly typed types which are adoped by Javascript using "strict" operator and it shares many concepts and syntax with typescript. This is why porting code from AS3 to Javascript is easy, but to Typescript is even easier.

Following I moved all the old ActionScript 3 code to make it available for posterity.

How to Remove an Item from an Array in AS3

The Array class in actionscript 3 don’t provide a method to remove a specified object.  To achieve it we have to search and get the index of the object in the array using indexOf method and to remove it using splice method:

public static function removeFromArray(obj:Object, arr:Array):void
    {
        var index:int = arr.indexOf(obj);
        if (index >= 0)
            arr.splice(index,1);	
    }	

How To Create A Rectangle Sprite in AS3

When you create AS3 projects in flex builder or other programs you’ll need simple shapes and sprites on the fly. Here is a simple method to create them:

public static function rectangleSprite(w:Number, h:Number, fillColor:uint
                    , borderColor:uint, center:Boolean = false):Sprite
    {
        var rectangleSprite:Sprite = new Sprite();
            
        rectangleSprite.graphics.lineStyle(1, borderColor)
        rectangleSprite.graphics.beginFill(fillColor);

        if (center)
            rectangleSprite.graphics.drawRect(0,0,w,h);
        else
            rectangleSprite.graphics.drawRect(-w/2,-h/2,w,h);

        rectangleSprite.graphics.endFill();
            
        return rectangleSprite;		
    }							

How To Open an URL in AS3

Here is a little snippet shat shows how to open an url in a new window from as3. If you want to open the link in the same window, simply replace “_blank” parameter with “”;

import flash.net.URLRequest;
    import flash.net.navigateToURL;

    ...
    navigateToURL(new URLRequest(url), "_blank");
    ...

How to Embed images in AS3

There are a few options to display images in flash applications.

  1. Load directly from code an image file from and url location.
  2. Embed the images directly in the as3 code using Embed annotation
  3. Import resources in flash and export them as swc files, then use them where you need them.
[Embed(source="../media/image.png")]
    public static var ImageCls:Class;

    protected function showImage():void
    {
                var bitmap:Bitmap = new ImageCls();

                // get a new BitmapData object:
                var bd:BitmapData = new BitmapData(bitmap.width, bitmap.height);
                bd.draw(bitmap);

                // get a new BitmapData object with alpha channel:
                var bdAlpha:BitmapData = new BitmapData(bitmap.width, bitmap.height);
                bdAlpha.draw(bitmap, null, null, BlendMode.ALPHA);
    }

DisplayObject Sprite MovieClip Class Hierarchy

The following diagram contains the structure of class objects from flash Action 3. Since flash is descoped, CreateJS, an open source javascript framework, backed up by Adobe, can be used instead to create HTML5 games. CreateJS implemented a similar class structure including DisplayObject, Sprite, Movieclip. You can check the CreateJS Class Hierarchy

The class hierarchy of the descendants of DisplayObjects

The class hierarchy of the descendants of DisplayObjects

Get The Class Of An Object In AS3

If you used to work with reflection in other languages like c# or java, you know that getting the object type might be useful. In addition with the operators “is” and “as” that are used to check if an object is a of a specific class or to cast it to a specific class there are 2 useful functions that will give us the class of a specific object. The first function getQualifiedClassName located in flash.utils. will return the class name as a string. The second function located in the same package, getDefinitionByName will return the Class object based on the string returned by the first function:

static function getClass(obj:Object):Class 
{
    return getDefinitionByName(getQualifiedClassName(obj)) as Class;
}

Then if you want to see if 2 objects are of the same class:

if (obj1 is getClass(obj2)) {
    trace(“The objects are of the same class...”);
}

Add Auto-Hide functionality to Sprite and MovieClip objects in AS3

Auto-Hide might be useful when you deal with situations when you have too many controls on a screen and you just want to hide those which are not used so often to have enough space in the main screen.

A simple option to implement would be to use MouseEvent.MOUSE_OVER and MouseEvent.MOUSE_OUT. Normally, only a margin of the clip should be visible in a margin of the screen. When the mouse is moved over the visible part of the clip, it is “shown” (moved entirely to visible area). When the mouse is moved out, the clip is “hidden”(moved mostly outside of the visible area).

public class MyScene extends Sprite
{
    private var panel = new MyPanel(); // a standard Sprite or MovieClip

    // class contructor
    public function MyScene()
    {
        // the panel is added to this class, but this code works as well
        // if the panel is added to another Sprite/MovieClip
        this.addChild(panel);

        panel.addEventListener(MouseEvent.MOUSE_OVER, mouseOverPanel);
        panel.addEventListener(MouseEvent.MOUSE_OUT, mouseOutPanel);
    }

    public function mouseOverPanel(e:MouseEvent):void
    {
        panel.x = 0;
        // each time the panel goes into shown mode it should be on top of
        // all the other clips to make use its visible:
        panel.parent.addChildAt(panel, panel.parent.numChildren);
    }

    public function mouseOutPanel(e:MouseEvent):void
    {
        panel.x = -90;
    }
}

The same functionality could be added inside the panel class in case we have access to it:

public class MyScene extends Sprite
{
    private var panel = new MyPanel(0, 50); // a standard Sprite or MovieClip

    // class contructor
    public function MyScene()
    {
        // the panel is added to this class, but this code works as well
        // if the panel is added to another Sprite/MovieClip
        this.addChild(panel);
    }
}

public class MyPanel extends Sprite
{
    private var baseX:int;

    public function MyPanel(x:int, y:int)
    {
        super();
        
        this.x = x;
        this.y = y;
        this.baseX = x;

        this.addEventListener(MouseEvent.MOUSE_OVER, mouseOver);
        this.addEventListener(MouseEvent.MOUSE_OUT, mouseOut);		
    }

        private function mouseOver(e:Event):void
        {
            this.x = baseX + this.width - 11;
            this.parent.addChildAt(this, this.parent.numChildren);
        }
        
        private function mouseOut(e:Event):void
        {
            this.x = baseX;
        }
}

As you can notice the second version of code contains a baseX memeber. This is the default x when the panel is in “hidden” mode. This is just and example how the parameter can be used to position the panel in the left margin. With minor changes it can be used to position the panel on the right margin of the screen or a baseY member can be added to put the panel on the top/bottom margins or in the corners.

This code can be “decorated”/changed:

  • using Tweens to add animations when the panel is shown/hidden.
  • using MouseEvent.ROLL_OVER and MouseEvent.ROLL_OUT instead to activate the menu when other objects are on top of the panel in hidden mode.
  • using panel.alpha = 0 when the panel is an “hidden” mode. This way the panel object will receives the mouse over/out events without being visible.

Convert Hex To/From int/uint in As3

In as3 it might be a simple and convenient way to store all sort of variables as String. When you have to store or transfer intergers (int or uint) it’s very easy to keep them in hexadecimal values. For example an array of integer can be stored in a comma separated string or in a string of values of the same length. For the first case everything is trivial. In the second case we have to take care when we serialize the integer values to prefix them with zeros so all of them will have the same length.

All we have to do to transform an integer to a hex string is to use toString() method.

trace(myint.toString(16));

Then to do get the int from a string we can use the parseInt global function:

trace(parseInt(str, 16));

If we want to have the same dimension for all of them we should use some helper functions to prefix the strings with zeros when necessary. The following example transforms the integers in strings of length of 3(min 000, max FFF).

/**
 * transform and int to a hex fixed width string prefixing it with zeros if required
 */
static private function intTo3Str(i:int):String
{
    return extendStr((i).toString(16).toUpperCase(), 3 );
}

/**
 * extends a string to a specified length by adding extra characters before or after
 * 
 */
static private function extendStr(str:String, len:int, c:String = '0', prefix:Boolean = true):String
{
    var extraLength:int = len - str.length;
    var extra:String = '';
    
    for (var i:int = 0; i < extraLength; i++)
        extra += c;
    
    if (prefix) return extra + str;
    else	    return str + extra;
}		

The same code can be used for colors but 6 should be used instead of 3, and preceding '#' or '0x' could be also taken in consideration.

Shuffle/Randomize Array/Vector in AS3

As3 Array/Vector classes don’t provide an implemented method to shuffle/randomize them. However, that’s not a hard task to do and there are quite a few methods to implement such an algorithm. One of the easiest methods is called Fisher-Yates shuffle. Probably it’s not the fastest way to shuffle an array, but it does not require extra memory. You need to traverse the array a single time.

Here is the code to shuffle an array:

public static function shuffleArray(arr:Array):void
{
    for (var i:int = arr.length - 1; i >= 1; i--)
    {	
        var j:int = Math.floor(Math.random() * i);//j ← random integer with 0 ≤ j ≤ i
        var temp:* = arr[j];
        arr[j] = arr[i];
        arr[i] = temp;
    }
}

And here if you want to shuffle a vector:

public static function shuffleArray(vec:Vector.<*>):void
{
    for (var i:int = vec.length - 1; i >= 1; i--)
    {	
        var j:int = Math.floor(Math.random() * i);//j ← random integer with 0 ≤ j ≤ i
        var temp:* = vec[j];
        vec[j] = arr[i];
        vec[i] = temp;
    }
}

Center/Align Vertically Text in a TextField Control

Depending whether you are using the classic TextField control and the TLFTextField newly introduced in Flash 10, you can choose one of the following options:

public static function centerVerticallyTF(textField: TextField): void 
{
    // because we're going to change the original position of the TextField
    // we want to make sure it doesn't cover other controls:
    textField.parent.setChildIndex(textField, 0);

    // new we change the position of the TextField so the text will be shown in the middle
    textField.y += Math.round((textField.height - textField.textHeight) / 2);
}

If we are using an TLFTextField instead of the classic TextField, it’s getting easier, because we have the vertical align feature implemented by the control:

import flashx.textLayout.formats.VerticalAlign;

public static function centerVerticallyTF(textField: TLFTextField ): void {
    myTextField.verticalAlign = VerticalAlign.MIDDLE;
}

Importing Spritesheets in Flash to Export them as MovieClips in SWC Libraries

[player-plane]

There are several reasons we might have to export resources from flash:

  • to create libraries to reuse them in other flash projects
  • to use Flash Builder or Flash Develop for writing code and Flash to create graphical assets
  • to use swc libraries in haxe projects

Lets take the following sprite:

player-plane

  1. Create a new flash project save it and import the following image in library or simply drag and drop it in flash. In both the cases the image will appear in the library and an image:

aeroplane-sprite

  1. Using the Rectangle Primitive Tool draw a rectangle of the dimensions of one frame in the sprite:

rectangle0primitive-tool

  1. Now make sure the rectangle has no border and set the fill to Bitmap Fill and select the imported image to fill. In following picture the rectangle is a little bit larger than the actual frame to get an idea of what bitmap fill means:
bitmap-fill
  1. Now right click on the rectangle and convert it to Symbol:
convert-to-symbol

… and in the newly open dialog set the name of the MovieClip object. In order to export the plane resource, make sure the export to actionscript is checked.

plane-res

  1. Double click on the created MovieClip and add 3 more Keyframes. Now we have to change the rectangle in the first and third frames so it will result in an animated MovieClip.  To do so select the Gradient Transform Tool:

GradientTransform

 

… and re-position the bitmap fill so the first frame from the spreadsheet is displayed. Repeat the operation for the third frame so in the end the MovieClip will look like this:

PlaneSymbol

6 .Open File > Project Settings… and check the SWC option so the classes marked to be exported to AS at point 3 will be exported in the swc.
Export

 

    Snippets

Action 3 Example Code and Snippets

ActionScript 3, developed by Adobe for Flash, originates from ActionScript 2, a Javascript variant. It uniquely adopted the ECMA4 standard that Javascript skipped. AS3 introduced strongly typed types, now in Javascript via the "strict" operator. Its syntax similarity to TypeScript simplifies code porting from AS3 to Javascript or TypeScript.