Drawing shapes with AS2

A shape that we draw with actionscript doesn't have to stay static. In this second part, we will create a dynamic shape.

1. Create a new Flash document following the instructions from part1.

2. Add this code to the "Actions" panel.

for (var i:Number=1; i<5;i++){
this.createEmptyMovieClip("drag"+i+"_mc", this.getNextHighestDepth());
this["drag"+i+"_mc"].moveTo(10, 10);
this["drag"+i+"_mc"].lineTo(20, 10);
this["drag"+i+"_mc"].lineTo(20, 20);
this["drag"+i+"_mc"].lineTo(10, 20);
this["drag"+i+"_mc"].lineTo(10, 10);

We created a for loop with which we created 4 squares named, drag1_mc, drag2_mc, drag3_mc, drag4_mc. Note this particuliar way to access the newly created movieclips, this["drag"+i+"_mc"] , this refers to the root of the flash file where you can access any movieclip in "array" style. We also set a behavior for these new movieclips, onpress and onrelease. When we will click and hold on one of these movieclips, we will be able to drag them, when we will release them, they will stay where they are.

3. You can already test this movie and drag these little black moviclips on the stage.

4. but we will use these movieclips to draw a shape and then play around with the shape, so now we need to place these black movieclips around the stage:

5. copy and paste this code after the code we already put:


6. We can set the position of a moviclip using its _x and _y properties. This is what we do here. We reference the movieclip and access the property using dot notation then assign a value. Here is the result:

7. Now let's draw the dynamic shape. To make it dynamic we need to use a dynamic event or a setInterval() (like in javascript), I chose to use an onEnterFrame event. Copy and paste this code after the code we have so far:

this.createEmptyMovieClip("square_mc", 1);
square_mc.moveTo(drag1_mc._x+drag1_mc._width, drag1_mc._y+drag1_mc._height);
square_mc.lineTo(drag2_mc._x+drag2_mc._width*2, drag2_mc._y+drag2_mc._height);
square_mc.lineTo(drag3_mc._x+drag3_mc._width*2, drag3_mc._y+drag3_mc._height*2);
square_mc.lineTo(drag4_mc._x+drag4_mc._width, drag4_mc._y+drag4_mc._height*2);
square_mc.lineTo(drag1_mc._x+drag1_mc._width, drag1_mc._y+drag1_mc._height);

We use a dynamic event (onEnterFrame) to update regularly our screen. We draw a shape using our little black movieclip coordinates as references. Now you can test the movie and drag the little black squares around to play with this dynamic shape!

Contact me if you have any issues when trying this tutorial.