Actionscript Basics – Loops

loops

Loops are very similar to conditional statements. However a loop will keep executing what is inside of it until its condition ceases to be true.  Perhaps the most notorious actionscript loop is the “for loop”. It looks something like this-

Start a new Flash File (actionscript 3.0), and on the first keyframe, paste the following code into the actions window:

for(var i:uint = 0; i < 10; i++){
 
   trace(i);
 
}

Lets dissect what is happening here in the first line. The “for” sets up the loop.

var i:uint = 0″ creates a variable of type uint (an “unsigned integer” meaning an integer that is not negative).

“i < 10" is the condition of the loop. It will continue to loop as long as variable "i" is less than 10.

"i++" adds 1 to the value of the "i" variable every time it loops.

Practical Example:

In this example we will use a loop to dynamically generate an image. Each time flash passes through the loop it draws a line to a random position with a random colour and a random size.  The end result looks like this:

The Flash plugin is required to view this object.

If you refresh this web page you will notice that the image will have changed since it is created using random variables.

Download .FLA source file

This entry was posted in Actionscript, Tutorials and tagged , , , . Bookmark the permalink. Trackbacks are closed, but you can post a comment.

5 Comments

  1. lsteel
    Posted March 21, 2009 at 11:03 am | Permalink

    Hey Jess,

    I tried to add a glow filter to the output objects, so I added the last line to the following code… but yeah it’s not that easy…. how would I do that?

    myImage.graphics.lineStyle(myRandomWidth, myRandomColor);
    myImage.graphics.lineTo(myRandomX, myRandomY);
    myImage.graphics.new GlowFilter();

  2. admin
    Posted March 22, 2009 at 11:11 am | Permalink

    Here’s a version of same project with a glow filter applied to myImage sprite which contains all lines.
    http://flashart.ca/wp-content/uploads/2009/03/drawingapi1.fla

    Here’s a version of a similar project with glow filters applied to each line. Since a filter MUST be applied to display object like a sprite or movieclip rather than a vector line- each of the lines are added to sprites which live inside myImage sprite.

    http://flashart.ca/wp-content/uploads/2009/03/drawingfilters1.fla

  3. Len Steel
    Posted March 22, 2009 at 3:47 pm | Permalink

    The second version is WAY cool!

    I’ll look at the code and try to figure out why the lines are all curved and why they all share a common origin.

    Thanks for getting back.

  4. lsteel
    Posted March 22, 2009 at 3:51 pm | Permalink

    OK… that was easy… I like the updated version… it’s a digital bouquet!

  5. admin
    Posted March 22, 2009 at 5:31 pm | Permalink

    Curves rule.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*