How to dispatch a custom event in Actionscript 3

This is going to be a very simple example of how to dispatch an event. In actionscript 3, you dispatch an event by extending the EventDispatcher class. I’m not going to get into a big complicated explanation right now, but I will show you a couple of simple examples.

One good thing about the Sprite class is that it already extends the EventDispatcher class, so if you are working from your document class, or your class extends Sprite/Movieclip, you can use this anywhere in your class:

// Declare at the top...
public static const CUSTOM_EVENT:String = "customEvent";
// ... Somewhere in your class...
dispatchEvent(new Event(CUSTOM_EVENT));

Let’s say for example you have the following class:

package{
   
    import flash.display.Sprite;
    import flash.events.EventDispatcher;
   
    public class Cat extends Sprite{
       
        public static const MEOW:String = "meow";
       
        public function Cat(){         
        }
       
        public function meow(){
           
            dispatchEvent(new Event(MEOW));
        }
    }
}

Now create an instance from your timeline:

var cat:Cat = new Cat

next:

cat.addEventListener(Cat.MEOW, doSomething);
cat.meow();

function doSomething(event:Event){
    trace("The cat is hungry!");
}

Ok, so this really doesn’t do anything useful, but you can see how you could use this idea to broadcast events from your objects. This is by no means comprehensive, but I have noticed that this simple concept has eluded a lot of people. Later I will write a more robust tutorial showing how to extend the EventDispatcher class and do some cool stuff.

How to create an AS3 game grid

One of the things that you have to do a lot when developing grid based games in Actionscript 3 is obviously lay out the grid. This is confusing to a lot of people but in flash, it is really quite simple. I created a simple class just for this blog to demonstrate how this can be achieved.

Here is the Actionscript 3 class, and then an explanation:

package com.frigidfish{
   
    import flash.display.Sprite;   
   
    public class Grid extends Sprite{
       
        public var rows:uint;
        public var cols:uint;
        public var cell:Array = new Array();
        public var plot:Array = new Array();
       
        public function Grid(displayObject:*,rows,cols, spacer){
           
            this.rows   = rows;
            this.cols   = cols;
           
            populateCells(displayObject,spacer);
            plotCells(cell);
           
        }
       
        private function populateCells(displayObject:*,spacer:int){
           
            var iterator:uint = 0;
            for(var c:uint = 0;c<cols;c++){
                for(var r:uint = 0;r<rows;r++){                                        
                    cell[iterator] = new displayObject;
                    cell[iterator].y = cell[iterator].height  * r + (spacer*r);
                    cell[iterator].x = cell[iterator].width * c + (spacer*c);
                    addChild(cell[iterator]);      
                    iterator++
                }
            }          
        }
       
        private function plotCells(cell:Array){        
           
            var iterator:uint = 0;
            for(var c:uint = 0;c<cols;c++){
                plot[c] = new Array;
                for(var r:uint = 0;r<rows;r++){                
                    plot[c][r] = cell[iterator];
                    iterator++                 
                }
            }          
        }
    }
}

Example usage:

import com.frigidfish.Grid;

var gameGrid:Grid = new Grid(Token,5,5,5);
addChild(gameGrid);


// There are 2 ways you can access the grid.
// by cell number (count 20 cells col by col):
gameGrid.cell[20].visible = false;

// or by plot info. if you count over 2 cols, and one
// row down, you'll see that this line makes the grid
// item invisible.
gameGrid.plot[2][1].visible = false;

Ok, so this is a very simple as3 class that can be built upon to do a lot of things. For example you could add a dynamic text field to your display object, and use the iterator in grid.as to add numbers to each cell.

You could use this as a starting point for a match type game or an array of other puzzle ideas. The point of this is just to help you understand how the grid is generated.

Let’s quickly go through the grid class:

The first thing we do is create 4 variables (lines 8-11).

rows and cols are passed to the constructor along with the class/display object that you want to instantiate and a spacer number. Note that in this class it is assumed that whatever you pass it as your display class must be displayable.

For this example, I just made a quick movieclip and called it Token, and selected ‘export for Actionscript’ in it’s properties.

Next is the constructor. As I said before, this requires 4 parameters:

your library item or class to display, rows (how many rows do you want) cols (how many columns do you want), space in pixels between display objects

the populateCells function does the meat of the work.

we create an iterator and start it at 0.
next we loop through each column.
for each column we add all of the rows:
1. create a new instance of the supplied display object and add it to the cell array
2. set the y position of the display object to it’s height x the number of the current row, + spacer
3. set the x position of the display object to it’s width x the number of the current column + spacer
4. Since this class extends Sprite, it is instantiated as a Sprite so we call just add the cell to it using the addChild() method
5. add 1 to the iterator and continue the loop.

notice that a key to making the spacer work properly is multiplying it by the row or the column. If you were to just ‘add’ spacer without multiplying by the row/col you would not achieve the desired result.

Next we execute the plotCells method. This creates an extra way to find the cell that you want. It sets up a 2 dimensional array and adds the cells to it so that you can access them by plotting coordinates.

first it creates an iterator and sets it to 0.
next we look through the length of the cols variable
now we create a new array and assign it to the plot array at the current column
for each number in cols, we iterate through all rows.
finally we assign each cell from our cell array to the proper plot coordinates.
add 1 to the iterator and process the next column.

So basically:
plot[0][0] = cell[0]
plot[0][1] = cell[1]
plot[0][1] = cell[2]


and so on. if you made a 5×5 grid, column 2, row 0 would be:
plot[2][0] = cell[10]

well, that’s it!
Hope you find this useful in your Flash Actionscript 3 projects.

Download this project as a working example here.

Load AS2 SWF into your AS3 Project

There is a Flash game that I have been working on that I’ve had to load into an as3 interface and I noticed that my previous class will not work to do this.

There were a few modifications that I had to make… Here is the Actionscript 3 class:

// SWFLoader Class by Rick Nuthman
// 2.16.10
//
// Usage:
/*
var game:SWFLoaderAs2 = new SWFLoaderAs2("yourSwf.swf",20,0)
game.dispatcher.addEventListener("ready", gameLoaded);
function gameLoaded(event:Event){
   
    addChild(game);
}
*/


package com.frigidfish{

    import flash.display.Sprite;
    import flash.display.Loader;
    import flash.events.Event;
    import flash.net.URLRequest;
    import flash.events.EventDispatcher;       

    public class SWFLoaderAs2 extends Sprite {     
       
        public var dispatcher:EventDispatcher   = new EventDispatcher();
        private var contentLoader:Loader;      
       
       
        public function SWFLoaderAs2(pathToTheContent,x,y) {
           
            this.x = x;
            this.y = y;
            loadSWF(pathToTheContent);
        }
           
        private function loadSWF(pathToTheContent):void {
           
            var request:URLRequest  = new URLRequest(pathToTheContent);
            contentLoader           = new Loader();
            contentLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,swfLoaded);
            contentLoader.load(request);
        }

        private function swfLoaded(e:Event):void {
           
            addChild(contentLoader);
            dispatcher.dispatchEvent(new Event("ready"));                  
        }
    }
}

usage:

var game:SWFLoaderAs2 = new SWFLoaderAs2("yourSwf.swf",20,0)
game.dispatcher.addEventListener("ready", gameLoaded);
function gameLoaded(event:Event){
   
    addChild(game);
}

This will certainly work to load an as2 swf into your as3 project,
but keep in mind that you will not be able to access methods and properties of your as2 swf.
I will be updating this class or adding another to make this possible. In the meantime,
Grant Skinner has created this to make the job a snap!

Quick and easy GetURL class / actionscript 3 urlrequest

Here is a quick basic flash url loader for quickly adding links to buttons and movie clips in Actionscript 3:

// GetURL Class by Rick Nuthman
// 10.4.09
// Usage:
// new GetURL("url", "target");

package com.frigidfish{
   
    import flash.net.*;
   
    public class GetURL{
       
        private var request:URLRequest;
       
        public function GetURL(url:String, target:String = '_self'){
           
            request = new URLRequest(url);         
            navigateToURL(request, target);
           
        }
    }
}

It’s just a bare bones script that works like the old getURL() method from actionscript 2.
It defaults to opening the url in a blank page, but you can change this by modifying the 2nd parameter.

import com.frigidfish.GetURL;

// you can add it right to an event listener for a button or movieclip

yourButton.addEventListener(MouseEvent.CLICK, function(){ new GetURL("your_url.html", "_self")});

// or by itself
new GetURL("your_url.html");

I like using this because it makes the code a lot cleaner and easier to read when you have a bunch of links to deal with in Flash. Enjoy!

Load SWF via Actionscript 3 with this class

Here is a class that you can use to load swf’s into an object that you can display or do whatever you’d like with:

// SWFLoader Class by Rick Nuthman
// 2.10.10
//
// Usage:
/*
var mySWF:Object;
mySWF = SWFLoader.create("urlToSWF.swf", 0,0);
mySWF.dispatcher.addEventListener("ready", displaySwf);
function displaySwf(event:Event){
    addChild(mySWF.swf);
}
*/


package com.frigidfish{

    import flash.display.Sprite;
    import flash.display.Loader;
    import flash.events.Event;
    import flash.net.URLRequest;
    import flash.events.EventDispatcher

    public class SWFLoader{        

        public function SWFLoader() {
        }

        public static function create(url, x=0,y=0):Object {
           
            var loaded:Event                = new Event("ready");
            var dispatcher:EventDispatcher  = new EventDispatcher();
            var swf:Sprite                  = new Sprite  ;
            var mLoader:Loader              = new Loader  ;
            var obj:Object                  = new Object;
           
            obj.swf = swf;
            obj.dispatcher = dispatcher;
           
            swf.x = x;
            swf.y = y;
           
            var mRequest:URLRequest = new URLRequest(url);
            mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,swfLoaded);

            mLoader.load(mRequest);

            function swfLoaded(event:Event) {
                var target = event.currentTarget.content;              
                swf.addChild(target);  
                dispatcher.dispatchEvent(loaded);
            }
           
            return obj;
        }
    }
}

You don’t need to make an instance of the class, just use the static function ‘create’ like so:

var mySWF:Object;
mySWF = SWFLoader.create("urlToSWF.swf", 0,0);
// You can replace 0,0 in the previous line with
// initial x,y coordinates for your swf
mySWF.dispatcher.addEventListener("ready", displaySwf);
function displaySwf(event:Event){
    addChild(mySWF.swf);
}

I have been using this class to load a bunch of swfs into an array of objects.. I built a preloader that says something like “loading foo.swf…” for each swf as they are loading. Then when the “ready” event has fired for all of the swfs I add them all to a container sprite and display them.