Monday, October 26, 2009

Create a Dynamic and Interactive Message Board in ActionScript 3

This tutorial is on a project made by my friend Peter Blaho(
The message board will be dyanmic in the sense that it will load the text from an external XML file.
To start hit Ctrl+J to bring up the Document properties window. Set the width to 400 pixels and the heigh to 60. Set any background color.It won't be visible
Draw a 400x60 Rectangle with the color #F4EED4. Align its centre so that it completely covers the stage.
Create a new layer and name it Actions.

Now Hit Ctrl+F8 to bring up the New Symbol window. Set its name to trigger_left and select Export For Actionsript.Go to the Color Window and set the type to Linear.Set the color of the left end color marker to #F4EED4 and alpha to 100%. Set the right one to #F4EED4 and this time the alpha to 0%.

Draw a 60x60 square and go to the Align panel to align the left edge. It should look like this

Now repeat the same process but instead of the left orientaion, it should be right. Set the name as trigger_right. This should look like this

Open the New Symbol window again and set the name to trigger_bottom. Remember to select Export For Actionscript. Draw a 300x60 rectangle of any color. Align its centre and set its alpha to 0.

Now select the first frame of the Actions Layer and copy and paste the following code

// FlashVars
var flash_vars:Array = new Array();

var keyStr:String;
var valueStr:String;
var paramObj:Object = LoaderInfo(this.root.loaderInfo).parameters;
for (keyStr in paramObj) {
    valueStr = String(paramObj[keyStr]);
    flash_vars[keyStr] = valueStr;

var text_array:Array = new Array();
var curr_text_id:int = 0;
var text_speed:int = 2;
var text_speed_s:int = text_speed;
var margin:int = 10;

var myTextField:TextField = new TextField();
var myFormat:TextFormat = new TextFormat();

var trigger_left_t:trigger_left = new trigger_left;
trigger_left_t.x = 0;
trigger_left_t.y = 30;

var trigger_bottom_t:trigger_bottom = new trigger_bottom;
trigger_bottom_t.x = 200;
trigger_bottom_t.y = 30;

var trigger_right_t:trigger_right = new trigger_right;
trigger_right_t.x = 400;
trigger_right_t.y = 30;

// load xml
var xml_loader:URLLoader; //the xml loader
flash_vars['xml_path'] = 'message.xml';
//loadXML(flash_vars['xml_path'] + "?ticker=" + Math.random() * 1.000000E+010); //load the xml
loadXML(flash_vars['xml_path']); //load the xml
function loadXML(Uri:String):void {
    xml_loader = new URLLoader();
    xml_loader.addEventListener(Event.COMPLETE, on_complete);
    xml_loader.addEventListener(IOErrorEvent.IO_ERROR, on_error);
    xml_loader.load(new URLRequest(Uri));

function on_error(evt:ErrorEvent):void {
    trace("cannot load xml file");

function on_complete(evt:Event):void {
    text_array = get_xml_data(;
    myTextField.htmlText = text_array[curr_text_id].msg;
    myTextField.width = 0;
    myTextField.x = 400 + margin;
    myTextField.y = 16;
    myTextField.selectable = false;
    myTextField.autoSize = TextFieldAutoSize.LEFT;
    myFormat.color = 0x000000;
    myFormat.size = 24;

function get_xml_data(XMLData:String):Array {
    var menuXML:XML = new XML(XMLData);
    //just in case
    menuXML.ignoreWhitespace = true;

    //get XML item's entrys
    var XMLItems = menuXML.descendants("core");

    //load all items into an array
    var itemsArray:Array = new Array();
    var itemObj:Object;
    for(var i in XMLItems) {
        itemObj=new Object();
        itemObj.msg = str_replace('[', '<', str_replace(']', '>', XMLItems[i].@msg));
        itemObj.msg_link = XMLItems[i].@msg_link;
    return itemsArray;

function main_function(event:Event) {
    var max:int = myTextField.width;
    if (myTextField.x <= ((0 - max) - margin)) {

        if ((text_array.length - 1) > curr_text_id) {
        else {
            curr_text_id = 0;
        myTextField.x = 700 + margin;
        myTextField.htmlText = text_array[curr_text_id].msg;
        myTextField.autoSize = TextFieldAutoSize.LEFT;
    if (myTextField.x > 710) myTextField.x = 710;
    myTextField.x -= text_speed;

function text_speed_up(event:MouseEvent):void {
    text_speed *= 2;

function text_reverse(event:MouseEvent):void {
    text_speed = 0 - text_speed;

function text_normal(event:MouseEvent):void {
    text_speed = text_speed_s;

function text_stop(event:MouseEvent):void {
    text_speed = 0;

function str_replace(search, replace, string):String {
    var array = string.split(search);
    return array.join(replace);

addEventListener(Event.ENTER_FRAME, main_function);
trigger_left_t.addEventListener(MouseEvent.MOUSE_OVER, text_reverse);
trigger_left_t.addEventListener(MouseEvent.MOUSE_OUT, text_normal);
trigger_bottom_t.addEventListener(MouseEvent.MOUSE_OVER, text_stop);
trigger_bottom_t.addEventListener(MouseEvent.MOUSE_OUT, text_normal);
trigger_right_t.addEventListener(MouseEvent.MOUSE_OVER, text_speed_up);
trigger_right_t.addEventListener(MouseEvent.MOUSE_OUT, text_normal);

Hit Ctrl+Enter to test the movie.

Download the .fla file here

Upload your files for free at

Tuesday, September 22, 2009

Create an Advanced Explosion/Fireworks Effect

I will be using a 400x400 Stage with a background color of 0x222222.
In the root directory of the .fla file create a new folder and name it script. Now open you favourite text editor and copy and paste the following code

package script
import flash.display.Sprite;
import flash.utils.Timer;

public class Spark extends Sprite
private var spark:Sprite = new Sprite();

/*origination coordinates of the spark*/
private var X;
private var Y;

/*the Y coordinate at which the spark will busrst*/
private var burstPoint;

/*sppeds along the X and Y axes*/
private var xSpeed;
private var ySpeed;

/*whether the spark will burst or jus fade away*/
private var willBurst;

/*the size(width) of the spark*/
private var size;

/*gravity will be acting on all sparks.*/
private var gravity = 0.15;

/*flag the spark for removal*/
private var removeSpark = false;

*The Constructor takes parameters in the following order
X Coordinate,
Y Coordinate,
vertical Speed,
Horizontal Speed,

Only the first three are mandatory

public function Spark(xc:Number,yc:Number,brstPnt:Number,ySd:Number=2,



private function moveDown(e:Event)
/*if the spark is flagged for removal*/

/*Increment the Y axis speed to simulate gravity*/

/*Move the spark*/

Draw the spark and simulate the trail.
If the spark will ultimately burst it
has a shorter trail. The trail also
depends on the speed of the spark;
for(var i=0;i<5;i+=1)
/*reduce the alpha*/

the trail length will reduce as the
alpha falls to simulate a
simutaneous fade out and slow down


/*If the burst Point has been reached*/
if the spark does not have to burst
flag it for removal

the burst effect will be obtained by
creating a random number of instances
of the Spark class and sending them
in random directions;

{ /*number of fragments will range from 20-40*/
var burstFragments = 20+Math.ceil(Math.random()*20);
for(var j=0;j<burstfragments;j++)>
var d:Spark =new Spark(spark.x,burstPoint,burstPoint-100,-7+Math.random()*14,-7+Math.random()*14,false,2)
/*flag the original spark for removal*/


//class ends
//package ends

This will be your custom class. Save this file in the folder named "script", with the name "". Now open your .fla file and hit Ctrl+J to bring up the Document Properties window and set both the Width and Height to 400 and the Background Color to0x222222 (Black).
Click on Ok and then select the first frame of the layer and hit F9. In the Actions window that pops up, Copy the following lines of code.

import script.Spark;
function showSpark() {
/*random X coordinate of origin*/
var X = Math.random()*400;

variable xSpeed so that sparks originating
from the left side of the stage move towards
the right and vice-versa

var xSpeed = 0.05*(200-X);

random burst point so that each spark
bursts at a different level

var burstPoint = 50+Math.random()*100;

var d:Spark = new Spark(X,350,burstPoint,-15,xSpeed,true,3);

/*add a random shade to the spark*/
var color:ColorTransform = new ColorTransform();
color.blueMultiplier = Math.random();
color.greenMultiplier = Math.random();
d.transform.colorTransform = color;


Hit Ctrl+Enter To test the movie. The code will add only one instance of the Spark class to the stage. Add your own method to add more instances

Download the orginal source code files here

You can improve the code by adding sounds to each explosions

Saturday, September 19, 2009

Imitate the Flash CS4 Color Palette in Actionscript 3

Open your .fla file and hit Ctrl+J to bring up the Document Properties window. Change the height and width to 400 and 240 pixels respectively and the Background color to 0x000000(Black)
Select the first frame and Hit F9 to bring up the Actions window. Copy and Paste the following code

/*size of each small square representing a color*/
var squareSize=13;

/*number of small squares in each side of a color set*/
var paletteSize = 6;

/*parent sprite container*/
var palette:Sprite = new Sprite();
palette.x = 10;
palette.y = 45

/*the square whose color is to be changed*/
var colorSampler:Sprite = new Sprite();;,80,100,100);;

/*create the palette*/
for(var k=0;k<paletteSize;k++)
for(var i=0;i
for(var j=0;j
var square:Sprite = new Sprite();;,0,squareSize,squareSize);;
square.x = (squareSize+1)*paletteSize*(k%3)+i*(squareSize+1);
square.y = (squareSize+1)*paletteSize*(Math.floor(k/3))+j*(squareSize+1);
/*add a gradual color to each small square.
By this distribution, the palette will have 6
color sets each made up of 6x6 small
squares. In all of these color sets there will
be an increasing amount of the GREEN mask along
the horizontal direction, and the BLUE mask along
the vertical direction. The red mask is distributed
over these 6 sets.

var color:ColorTransform = new ColorTransform();
color.greenMultiplier = i/(paletteSize-1);
color.blueMultiplier = j/(paletteSize-1);
color.redMultiplier = k/(paletteSize-1);


/*listen for a click on the small square*/

/*change the color of the square*/
function clickHandler(e:MouseEvent) {

/*the color masks are actually found by processing
the position of the clicked small square*/

var X=e.currentTarget.x;
var Y=e.currentTarget.y;
var Z=Math.floor(X/paletteSize)+Math.floor(Y/paletteSize)*3;

/*apply the new color*/
var color:ColorTransform = new ColorTransform();
color.greenMultiplier =X/(paletteSize-1);
color.blueMultiplier =Y/(paletteSize-1);
color.redMultiplier = Z/(paletteSize-1);

Thats it!! Hit Ctrl+Enter to Test your movie.
Change the code to make the palette more detailed and sensitive.
Just like the color palette in Flash CS4, you can add a slider that darkens any given color. This can be achieved by gradually decreasing all the color masks simutaneously.

Wednesday, September 16, 2009

Create a very Realistic, custom Class, Dynamic Smoke Effect in Actionscript 3

In the root directory of the .fla file create a new folder and name it script. Now open your favourite text editor and copy and paste the following code

*The smoke effect is achieved by creating small circles
*They are continuously moved upwards
*A BlurFilter is applied to make them look realistic
*As they float above their dimensions are increased and the alpha reduced
*Actually only 40 particles are present and they are continuosly
recycled to prevent the main memory occupied by the .swf file
from increasing.

package script{

import flash.display.Sprite;
import flash.display.Shape;
import flash.display.MovieClip;
import flash.filters.BlurFilter;
import flash.utils.Timer;

public class Smoke extends Sprite
/*this will be the parent container*/
private var smoke_mc:MovieClip = new MovieClip();

/*color of the smoke*/
private var color:uint;

/*radius of each smoke particle*/
private var partRadius:Number = 1;

/*BlurFilter for the smoke particles*/
private var blur:BlurFilter = new BlurFilter(8,8,2);

/*timer to attach smoke particles*/
private var timer:Timer = new Timer(100);

the constructor takes 3 parameters-
X and Y coordinates of the point of origination
and the color of the smoke

public function Smoke(xc:Number,yc:Number,col:uint)
/*attach the parent movieClip*/

/*assign the color*/

/*start the timer*/

/*listener for the timer. the function startSmoke
is called every 100 miliseconds*/


/*attaches one smoke particle to the stage*/
private function startSmoke(e:TimerEvent)
/*if 40 particles has been attached
stop attaching any more */

/*stop the timer*/

/*remove the timer listener*/

/*atach a particle to the parent movieclip*/

/*Create and return a fully formed smoke particle*/
private function smokeParticle():Sprite
var smokePart:Sprite = new Sprite();;

/*create the particle at a random point
between +2 and -2 pixels from the given
X coordinate*/

var randX = -2+Math.random()*4;,0,partRadius);;

/*blur the particle*/

/*add more randomness to the X coordinate*/
var randDist = -10+Math.random()*20;

/*move the particles*/

return smokePart;

move and resize the particles
change the values to see their
effects on the smoke

private function moveUp(e:Event)
/*if the particle is visible*/
/*move it upwards*/

/*increase the width*/

/*incraese the height at a lesser rate*/

/*reduce the alpha*/
/*if the particle is not visible
restore Y to 0 ,X to a random
value, width and height to the
original radius and the alpha to 1*/


var randDist = -5+Math.random()*10;




This will be your custom class. Save this file in the folder named "script", with the name "". Now open

your .fla file and hit Ctrl+J to bring up the Document Properties window and set the Width and Height to 200

and 300 and the Background Color to 0x000000 (Black).
Click on Ok and then select the first frame of the layer and hit F9. In the Actions window that pops up, Copy

the following lines of code

/*import the custom class*/
import script.Smoke;

/*call the constructor to create a new instance of the Smoke class
change the X and Y coordinates and the Color of the smoke here.

var smoke:Smoke=new Smoke(100,150,0xBBBBBB);

/*add the instance to the stage*/

Thats it. Hit Ctrl+Enter to test your movie.
Add Objects to your movie and create multiple instances with different colors for a more complicated effect

Download the source files here

Saturday, September 12, 2009

Create a 3-D Image Reflection Effect with and advanced apllication of Bitmaps

This tutorial is insprired by the one i saw here but my application is actually different. I will use flters instead of masks
The 3-D effect is achieved with the application of the flash.display.BitmapData class and various Filters.

First we import an image on to the libray Through File->Import->Import to Library.. .here I am using a 200x200 album cover of Flipsyde's first album "We the People".

Now go to the library and right click on the image and select Properties. In the Linkage properties select Export For Actionscript and set the class name as pic;

Create a new movieclip to rotate your image and its reflection. Mine looks like this

Drag two instances of this on to the stage and rotate one to point to the right. give them instance names "l_mc" and "r_mc".

That done select the first frame of the Layer and copy and paste the following code

/*image dimensions*/
var imageHt=200;
var imageWd=200;

/*indicates the magnitude of rotation*/
var rot=0;

/*flags the direction of rotation*/
var goLeft:Boolean = false;
var goRight:Boolean = false;

/**load the image from the library into a bitmap data*/
var bitmap:BitmapData=new pic(imageHt,imageWd);

/*declare the container Sprites. "actual" will hold the image
"reflection" will hold the reflection and "container" will
hold these two*/

var container:Sprite = new Sprite();
var actual:Sprite = new Sprite();
var reflection:Sprite = new Sprite();

/*load the bitmap data into two bitmaps to
display the image and its reflection resp.*/

var imgage:Bitmap= new Bitmap(bitmap);
var refl:Bitmap = new Bitmap(bitmap);

Filters for the reflection. the parameters are
Blur Filter - (blurX,blurY,quality).
Bevel Filter - (distance, angle, highlight color,highlight alpha,
shadow color,shadow alpha,blurX,blurY,quality,
notice the filter is applied just to the container bitmap,
not the bitmap data itself.

var _blur:BlurFilter = new BlurFilter(3,3,1);
var _bevel:BevelFilter = new BevelFilter(50,90,0x000000,1,0x003366,.2,1,70,1,1,"inner");

/*attach the image to the top Sprite container*/
actual.x = -imageHt/2;
actual.y = 0;

/*flip the reflection along the X axis and attach
the image to the top Sprite container*/

reflection.rotationX = 180;
reflection.x = -imageHt/2;
reflection.y = 2*imageWd+1;

/*attach the top level container to the stage*/
container.y = 40;

/*this creates an improved rotational effect.
change the value of pp.fieldOfView to see
what happens*/

var pp:PerspectiveProjection=new PerspectiveProjection();

/*add listeners*/


/*start left rotation*/
function rotLeft(e:MouseEvent)

/*start right rotation*/
function rotRight(e:MouseEvent)

/*stop left rotation*/
function stopLeft(e:MouseEvent) {

/*stop right rotation*/
function stopRight(e:MouseEvent) {

/*rotate by the given amount*/
function rotate(e:Event) {
else if(goRight)

Hit Ctrl+Enter to test your movie. Change the background to suit your visual needs.

Download the .fla file here


Thursday, September 10, 2009

Create a Funky Menu

We will create a nice menu with an advanced mouseOver handler for the buttons.

This tutorial is actually inspired by the pretty cool one I saw
But there the person used a special pre-scripted class called "TweenMax". I will try to do it with my own custom class. The animation is a little different because I haven't used the Tween Class at all.

To begin create a New Folder in your .fla root directory and name it "script". Inside it create a file with the name "". Copy and paste the follwing code in it. This will give you the custom class

package script{

import flash.display.Sprite;
import flash.display.Shape;
import flash.display.MovieClip;
import flash.display.DisplayObject;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFieldAutoSize;
import flash.geom.ColorTransform ;
import flash.utils.Timer;

public class menuButton extends Sprite
/*the parent movie clip*/
private var button:MovieClip = new MovieClip();

/*name of the button*/
private var buttonName:String;

/*X coordinate of the button*/
private var X:Number;

/*X coordinate of the button*/
private var Y:Number;

/*text field to display the name*/
private var buttonText_txt:TextField=new TextField();

/*timer to monitor the random movements*/
private var timer:Timer = new Timer(100);

/*the constructor takes 3 parameters,the button
name and the x and y coordinates */

public function menuButton(str:String, xc:Number, yc:Number)

/*create the button*/
public function getButton()
/*assign x and y coordinates*/
button.x = X;
button.y = Y;

/*create the background of a 8x4 array of
small squares*/

for(var i=0;i<4;i++)
for(var j=0;j<8;j++)
var rect:Sprite = new Sprite();;*9,i*9,8,8);;

/*format in which to display the name*/
var format:TextFormat = new TextFormat();
format.font = "verdana";
format.color = 0xFFFFFF;
format.size = 18;

/*create the text field and display the
button name*/

buttonText_txt.selectable = false;
buttonText_txt.text = buttonName;
buttonText_txt.autoSize = TextFieldAutoSize.LEFT;

/*attach the button to the stage*/

/*create mouse listeners*/

private function mouseOverHandler(e:MouseEvent) {
/*start the timer to start the random
movement of the background squares*/


/*loop through each of the small squares
set it to a random color and an alpha of 0.6*/

for(var i=0;i<button.numChildren-1;i++)
var obj:Object = button.getChildAt(i);
var color:ColorTransform = obj.transform.colorTransform;
var randx = -30+Math.random()*60;
var randy = -30+Math.random()*60;
/*multiplying by 2 gives brighter colors*/
color.redMultiplier = Math.random()*2;
color.blueMultiplier = Math.random()*2;
color.greenMultiplier = Math.random()*2;
obj.transform.colorTransform = color;
obj.alpha =0.6;

private function mouseOutHandler(e:MouseEvent) {
/*stop the timer and the random movements*/

/*restore previous values of x and y coordinates
and the color*/

for(var i=0;i<button.numChildren-1;i++)
var obj:Object = button.getChildAt(i);
var color:ColorTransform = obj.transform.colorTransform;
obj.transform.colorTransform = color;
obj.x = Math.floor((i%8)/9);
obj.y = Math.floor(Math.floor(i/8)/9);
alpha = 1;

/*move the background squares randomly*/
private function moveRandom(e:TimerEvent) {
for(var i=0;i<button.numChildren-1;i++)
var obj:Object = button.getChildAt(i);

/*find random values for x and y coordinates*/
var randx = -1+Math.random()*2;
var randy = -1+Math.random()*2;

/*assign the random coordinates*/



Now open your .fla file and hit Ctrl+J to bring up the Document Properties window.Change the height to 150 and the background color to 0x00000.
That done, select the first frame and hit F9. Copy and paste the following script

/*import the custom class*/
import script.menuButton;

/*this array will contain the names of all the buttons you want in your menu*/
var labels:Array=["Home","Gallery","Login","Submit"];

/*display the buttons*/
for(var i=0;i<labels.length;i++)
var b:menuButton = new menuButton(labels[i],100*(i+1),60);

Hit Ctrl+Enter to test your movie!

Download the .fla file

Wednesday, September 9, 2009

Create a XML Driven, dynamic Word Jumble Puzzle

We will make a game where the player has to unjumble a given jumbled word. The words will be stored in an external XML file so that words can be easily changed and/or added.

First we create the XML file. open your favourite text editor and copy in the following.

<?xml version="1.0"?>






























Save it as words.xml and then open your new .fla file. Remeber the .swf and .xml files should be in the same directory.

Hit Ctrl+J and bring up the Document Properties window and set the hieght and width to 200 and the background color to #99CC99.

Now select the Text Tool and draw a Dynamic text field. Go to the Propertoes Window and make sure the "Show Border around Text" and "Selectable" are not selected.Go to the Propertes window and type in its instance name as "jumble_txt" Now draw an Input text field with the "Show Border around Text" selected.This time its instance name will be "input_txt".Your Stage should look like this.

With the Text tool selected, draw two Static text boxes as label for the above fields, like so

Now hit Ctrl+F8 to bring up the New Symbol Window, change the name to "checker" and click OK. Draw you own button. Mine looks like this

Similarly draw another button. Name it "next"

Now go to the main stage and drag the two buttons onto the stage.

The instance name of the "checker" button should be check_mc and the other should be "next_mc"

That done Create a new layer and name it Actions. Select the first frame and hit F9. Copy and paste the following code.

var xmlLoader:URLLoader= new URLLoader();

/*load the xml file*/
xmlLoader.load(new URLRequest("words.xml"));

/*on completion of loading invoke the "parseXML" function*/
xmlLoader.addEventListener(Event.COMPLETE, parseXML);

var words:Array = new Array();

function parseXML(e:Event):void {
var i,j;
var menuLength;/*length of the word array*/

var XMLData:XML = new XML(;

menuLength = XMLData.word.length();

/*populate the globally defined array*/
for (i=0; i<len;i++)

/*show the jumbled word*/

var actualWord;/*the word being displayed in unjumbled form*/

var input;/*input typed in by the player*/

/*listen for mouse click*/

/*show a jumbled word to solve*/
function showWord() {
/*choose a random index of the words array
and choose the word.Thus we choose a random
word everytime*/

var randChoice = int(Math.random()*words.length);
actualWord = words[randChoice];

/*display the jumbled word from the random array index*/
jumble_txt.text = jumbled(actualWord);
jumble_txt.autoSize = TextFieldAutoSize.LEFT;

/*show the button if hidden*/

/*receive a string and return it after random jumbling*/
function jumbled(word:String):String {
var len=word.length;
var rand;
var c;
var wordArray:Array = new Array();
var jumbledWord:String = new String();

/*convert the string to an array to avail
better indexed access*/

for(var i=0;i<len;i++)

/*randomise the array. The algorithm
sequentually picks a letter and swaps it
with a random letter coming after it */

rand = i+int (Math.random()*(len-i));

/*reconvert array to string*/
for(i=0;i <len;i++)


/*return the jumbled string*/
return jumbledWord;

/*trim whitespaces from the given string*/
function trim(word:String):String {
/*remove from front*/
word = word.replace( /^\s*/g, "" );

/*remove from end*/
word = word.replace( /\s*$/g, "" );
return word

/*check the answer typed in by the player*/
function checkAnswer(e:Event) {

/*remove any whitespaces entered*/
input = trim(input);

/*remove anything typed in by the user*/

/*hide the clicked button*/

/*input is correct*/
jumble_txt.text = actualWord+" :-))";
else/*if input is wrong*/
jumble_txt.text = actualWord+" :-((";

/*show a new word*/
function newWord(e:MouseEvent) {

Hit Ctrl+Enter to test your movie!