Home  :  Notes Index  :  About/Contact  :  Downloads

A quick lookup for the ActionScript to perform various common Flash tasks, with references to pages at the site for further reading. Code is written assuming the movieclips being addressed are in the main timeline, and the code is in one main frame (either frame 1 or another frame with a stop action in it) of the main timeline.

General Movieclip Manipulation
1 Make movieclip circle_mc opaque when the mouse is not over it and change to 60% opacity when the mouse goes over it.

For more information:
Functions
Movieclip reference page
Responding to mouse events
circle_mc.onRollOver = function() {
   this._alpha = 60;
};
circle_mc.onRollOut = function() {
   this._alpha = 100;
};
2 Make movieclip plane_mc play when control movieclip play_mc is clicked.

For more information:
Playhead commands
Functions
See next example for generic version
play_mc.onRelease = function() {
   plane_mc.play();
};
3 Define a function to make plane_mc play. Assign that function to play_mc's onRelease event, so that when play_mc is clicked, plane_mc will play.

For more information:
see reference links above
function flyPlane() {
   plane_mc.play();
}
play_mc.onRelease = flyPlane;
4 Define a function to make plane_mc play only if it is currently "parked" in frame 1 (ie, frame 1 of plane_mc has a stop action). Assign the function to play_mc's onRelease event, so that when play_mc is clicked, if plane_mc is not already playing, it will play.

For more information:
Code Blocks, including If statements
Playhead commands
Functions
function flyPlane() {
   if (plane_mc._currentframe == 1) {
      plane_mc.play();
   }
}
play_mc.onRelease = flyPlane;
5 Make movieclip circle_mc fade to 60% opacity when the mouse goes over it and jump back to 100% when the mouse goes off.

For more information:
Functions
Responding to mouse events
Operators
circle_mc.onRollOver = function() {
   this.onEnterFrame = function() {
      if (this._alpha > 60) {
         this._alpha -= 10;
      } else {
         delete this.onEnterFrame;
      }
   };
};
circle_mc.onRollOut = function() {
   this._alpha = 100;
};
6 Declare a variable (property of the main timeline, and so available for use by any elements in the movie) named found, of type Boolean, and set its initial value to false.

For more information:
Declare and assign variables
Simple data types
var found:Boolean = false;
Assign properties to movieclips to hold information needed for click events
7 Create a property of movieclip bee_mc named flying and set its value to true.

For more information:
Movieclip reference page
Intro to classes
Declaration and assignment
bee_mc.flying = true;
8 Create a property associatedClip of movieclip c0 which is a pointer to box0 and use it to unhide box0 when c0 is clicked.

Examples of assigned properties in use:
Easing slider
Bee game
function unhide() {
   this.associatedClip._visible = true;
}
c0.associatedClip = box0;
c0.onRelease = unhide;
9 Create the same property for several control movieclips, c0 - c4, and use it to determine which movieclip (box0 - box4) each one should unhide when clicked.

For more information:
Code blocks, including for loops
For examples of this in use:
Easing slider
Group of buttons
function unhide() {
   this.associatedClip._visible = true;
}
for (var i=0; i < 5; i++) {
   this["c"+i].associatedClip = this["box"+i];
   this["c"+i].onRelease = unhide;
}
10 Create the same property for several control movieclips, c0 - c4, setting its value from an array of information, and using the property to determine what text to display in textfield page_txt when a control is clicked.

For more information:
Arrays
For an example of this in use:
Group of buttons
var controlInfo:Array = [
   "wake up", 
   "eat lunch", 
   "go home", 
   "walk the dog"
   ];
function showText() {
   page_txt.text = this.mytext;
}
for (var i=0; i < 5; i++) {
   this["c"+i].mytext = controlInfo[i];
   this["c"+i].onRelease = showText;
}
11 Use an array to hold pointers to the control movieclips, the text to display in textfield page_txt and pointers to the associated picture movieclip to set to 50% opacity when the control is clicked. Use the information in the array to assign appropriate properties to each control to define its click behavior.

For more information:
Arrays and Objects
For an example of this in use:
Group of buttons
var controlInfo:Array = [
   {ctl:wakeup_mc, text:"wake up", pic:alarm_mc},
   {ctl:eatlunch_mc, text:"eat lunch", pic:lunch_mc},
   {ctl:gohome_mc, text:"go home", pic:door_mc},
   {ctl:walkdog_mc, text:"walk the dog", pic:dog_mc},
   {ctl:sleep_mc, text:"fall asleep", pic:bed_mc}
   ];
function onClick() {
   page_txt.text = this.mytext;
   this.myclip._alpha = 50;
}
for (var i=0; i < controlInfo.length; i++) {
   controlInfo[i].ctl.mytext = controlInfo[i].text;
   controlInfo[i].ctl.myclip = controlInfo[i].pic
   controlInfo[i].ctl.onRelease = onClick;
}
12 The same example as above, using string representations of the movieclips, rather than pointers to the actual movieclips, in the array. In this example, the pic movieclips are inside movieclip frame_mc.

For more information:
Arrays and Objects
For an example of this in use:
Group of buttons
var cInfo:Array = [
   {ctl:"wakeup_mc", text:"wake up", pic:"alarm_mc"},
   {ctl:"eatlunch_mc", text:"eat lunch", pic:"lunch_mc"},
   {ctl:"gohome_mc", text:"go home", pic:"door_mc"},
   {ctl:"walkdog_mc", text:"walk the dog", pic:"dog_mc"},
   {ctl:"sleep_mc", text:"fall asleep", pic:"bed_mc"}
   ];
function onClick() {
   page_txt.text = this.mytext;
   this.myclip._alpha = 50;
}
for (var i=0; i < cInfo.length; i++) {
   this[cInfo[i].ctl].mytext = cInfo[i].text;
   this[cInfo[i].ctl].myclip = frame_mc[cInfo[i].pic];
   this[cInfo[i].ctl].onRelease = onClick;
}
Motion
13 Move movieclip ball across the stage at a constant number of pixels per frame, using ball's timeline to control the motion:

For more information:
Functions
Event handlers
var xspeed:Number = 5;
function moveRight() {
   this._x += xspeed;
}    
ball.onEnterFrame = moveRight;
14 Move movieclip ball across the stage at a constant number of pixels per frame. When ball hits a predefined right or left boundary, send it back the other way. Movieclip ball has an upper left registration point.

For more information:
Functions, If statements
Event handlers
Operators
var xspeed:Number = 5;
var leftbound:Number = 0;
var rightbound:Number = 300;

function moveRightLeft() {
   this._x += xspeed;
   if (this._x > rightbound - this._width) {
      this._x = rightbound - this._width;
      xspeed *= -1;
   } else if (this._x < leftbound) {
      this._x = leftbound;
      xspeed *= -1;
   }
}

ball.onEnterFrame = moveRightLeft;
15 Move movieclip ball across the stage at a random number of pixels (between 5 and 10) per frame. When ball hits a predefined right or left boundary, send it back the other way at a new random speed (between 5 and 10 pixels per frame). Movieclip ball has an upper left registration point.

For more information:
Functions, If statements
Event handlers
Math functions
Operators
Registration point
var xspeed:Number;
var leftbound:Number = 0;
var rightbound:Number = 300;

function randomBetween(a:Number, b:Number):Number {
   return a + Math.floor(Math.random()*(b-a+1));
}

function moveRightLeftRandom() {
   this._x += xspeed;
   if (this._x > rightbound - this._width) {
      this._x = rightbound - this._width;
      xspeed = -1 * randomBetween(5, 10);
   } else if (this._x < leftbound) {
      this._x = leftbound;
      xspeed = randomBetween(5, 10);
   }
}

xspeed = randomBetween(5, 10);
ball.onEnterFrame = moveRightLeftRandom;
16 Keep movieclip ball moving and bouncing off 'walls' at a fixed speed (number of pixels per frame) within a defined rectangular area (300 x 200 box at 0,0)

For more information:
pages above, plus Object Class
var bounds:Object = {L:0, T:0, R:300, B:200};
var xspeed:Number = 5;
var yspeed:Number = 5;

function moveInBounds() {
   this._x += xspeed;
   this._y += yspeed;
   if (this._x > bounds.R - this._width) {
      this._x = bounds.R - this._width;
      xspeed = -xspeed;
   } else if (this._x < bounds.L) {
      this._x = bounds.L;
      xspeed = -xspeed;
   } else if (this._y > bounds.B - this._height) {
      this._y = bounds.B - this._height;
      yspeed = -yspeed;
   } else if (this._y < bounds.T) {
      this._y = bounds.T;
      yspeed = -yspeed;
   }
}

ball.onEnterFrame = moveInBounds;
Drag and Test for Collisions
17 Make movieclip dragger_mc draggable within a 200 x 100 box on stage with its upper left corner 50 pixels from the right edge and down 40 pixels from the top edge of the stage.

For more information:
Drag movieclips, detect collisions
dragger_mc.onPress = function() {
   this.startDrag(false, 50, 40, 250, 140);
};
18 Make movieclip dragger_mc stop dragging when the mouse is released.

For more information:
Drag movieclips, detect collisions
dragger_mc.onRelease = 
dragger_mc.onReleaseOutside = function() {
   this.stopDrag();
};
19 Make dragger_mc draggable. If the (invisible, rectangular) bounding box around movieclip dragger_mc has hit the (invisible, rectangular) bounding box of target_mc when the mouse is released after dragging, set target_mc to 50% opacity. Otherwise set it to 100% opaque.

For more information:
Drag movieclips, detect collisions
dragger_mc.onPress = function() {
   this.startDrag();
}
dragger_mc.onRelease =
dragger_mc.onReleaseOutside = function() {
   this.stopDrag();
   if (this.hitTest(target_mc)) {
      target_mc._alpha = 50;
   } else {
      target_mc._alpha = 100;
   }
};
Load an external jpg or swf
20 Load "somepic.jpg" into movieclip holder_mc (on stage), showing a horizontal progress bar (bar_mc, on stage) during load, and sizing the jpg to 50% of its original size before displaying it.

For more information:
Load jpg or swf
var loader:MovieClipLoader = new MovieClipLoader();
function onLoadProgress(_mc, loaded, total) {
   var pct:Number = Math.round(loaded / total * 100);
   bar_mc._xscale = pct;
};
function onLoadInit(_mc) {
   bar_mc._visible = false;
   _mc._xscale = _mc._yscale = 50;
   _mc._visible = true;
};
loader.addListener(this);
bar_mc._xscale = 0;
holder_mc._visible = false;
loader.loadClip("somepic.jpg", holder_mc);
21 Load "mymovie.swf" in folder movies into movieclip player_mc (on stage), showing a percent loading message during load in textfield pct_txt, and calling an init function within the swf to start it once it's loaded.

For more information:
Load jpg or swf
var loader:MovieClipLoader = new MovieClipLoader();
function onLoadProgress(_mc, loaded, total) {
   var pct:Number = Math.round(loaded / total * 100);
   pct_txt.text = pct + "%";
};
function onLoadInit(_mc) {
   pct_txt.text = "";
   _mc.init();
};
loader.addListener(this);
loader.loadClip("movies/mymovie.swf", player_mc);
22 Load "movie.swf" into movieclip player_mc (on stage), showing a preloader clip (preloader_mc) that has been designed with a 100-frame sequence in it and a stop action in frame 1, during loading. A separate listener object is created instead of using the main timeline (or other current instance) as above. The swf is assumed to have a stop action in frame 1 and will be told to play when loaded.

For more information:
Load jpg or swf
Make 100-frame preloader movieclip
var loader:MovieClipLoader = new MovieClipLoader();
var lis:Object = {};
lis.onLoadProgress = function(_mc, loaded, total) {
   var pct:Number = Math.round(loaded / total * 100);
   preloader_mc.gotoAndStop(pct);
};
lis.onLoadInit = function(_mc) {
   preloader_mc._visible = false;
   _mc.play();
};
loader.addListener(lis);
loader.loadClip("movie.swf", player_mc);
Read text file from web server (or local file if running a Flash executable)
23 Read the contents of a (utf-8 encoded) text file and display exactly as is in dynamic textfield page_txt.

For more information:
Read text file
var lv:LoadVars = new LoadVars();

lv.onData = function(thetext:String) {
   page_txt.text = thetext;
}

lv.load("thetextfile.txt");  
24 Read the contents of a &var=value& formatted text file that looks like:

&name0=fuschia&val0=DE11E6&
&name1=limegreen&val1=00FF00&
etc

and save the contents in array paintcolors, converting the color value from a string to a number for later use.

For more information:
Read text file
var lv:LoadVars = new LoadVars();
var paintcolors:Array = [];

lv.onLoad = function(success:Boolean) {
   if (success) {
      var i:Number=0;
      while (this["name"+i]!=undefined) {
         paintcolors.push({ 
            myname:this["name"+i], 
            mycolor:parseInt(this["val"+i], 16)
         });
         i++;
      }
   } else {
      trace('problem reading file');
   }
};

lv.load("paintcolors.txt");  
25 Same example as above, using the array to color a number of swatch movieclips (swatch0, swatch1, etc) on stage, each of which contains a movieclip "dot" and a textfield "name".

For more information:
Read text file
Color class
var lv:LoadVars = new LoadVars();
var paintcolors:Array = [];

function setcolors() {
   var c:Color;
   for (var i=0; i < paintcolors.length; i++) {
      c = new Color(this["swatch"+i].dot);
      c.setRGB(paintcolors[i].mycolor);
      this["swatch"+i].name.text = paintcolors[i].myname;
   }
}

lv.onLoad = function(success:Boolean) {
   if (success) {
      var i:Number=0;
      while (this["name"+i]!=undefined) {
         paintcolors.push({ 
            myname:this["name"+i], 
            mycolor:parseInt(this["val"+i], 16)
         });
         i++;
      }
      setcolors();
   } else {
      trace('problem reading file');
   }
};

lv.load("paintcolors.txt");  
Read an XML file from the web server (or local file if running a Flash executable)
26 Read an XML file that looks like

<?xml version="1.0" encoding="utf-8"?>
<colors>
  <color name="fuschia" val="DE11E6" />
  <color name="limegreen" val="00FF00" />
</colors>

and create an array of colors which are used to color a number of swatch movieclips (swatch0, swatch1, etc) on stage, each of which contains a movieclip "dot" and a textfield "name" (as in the previous text file example).

For more information:
XML
Color class
var colorxml:XML = new XML();
var paintcolors:Array = [];

function setcolors() {
   var c:Color;
   for (var i=0; i < paintcolors.length; i++) {
      c = new Color(this["swatch"+i].dot);
      c.setRGB(paintcolors[i].mycolor);
      this["swatch"+i].name.text = paintcolors[i].myname;
   }
}

colorxml.onLoad = function(success:Boolean) {
   if (success) {
      var colors:Array = this.firstChild.childNodes;
      for (var i=0; i < colors.length; i++) {
         paintcolors.push({ 
            myname:colors[i].attributes.name,
            mycolor:parseInt(colors[i].attributes.val, 16)
         });
      }
      setcolors();
   } else {
      trace('problem reading file');
   }
};

colorxml.ignoreWhite = true;
colorxml.load("paintcolors.xml");