Chapter 4 - ClassFileExample.swf
This example demonstrates the use of ActionScript 2 class files. The code in the "SimpleSquare.as" class file is "imported" into the FLA. Once it is imported, the SimpleSquare class can be used just as if it were a built-in ActionScript class. User-defined classes extend the capabilities of ActionScript in a generalized, reusable way.
The complete example is available in the Downloads Center. The ActionScript code for this example is:
Main Timeline code:
import ch4.SimpleSquare;
var size = 20;
for (var i:Number = 0; i < 5; i++) {
for (var j:Number = 0; j < 5; j++) {
trace("Drawing square (" + i + ", " + j + ")");
var x_coord = i * (size + 5);
var y_coord = j * (size + 5);
var tempSquare:SimpleSquare =
new SimpleSquare(x_coord, y_coord, size, this);
tempSquare.draw();
}
}
ActionScript 2 class code:
class ch4.SimpleSquare {
// Properties
var coords:Object;
var name:String;
var size:Number;
var mc:MovieClip;
var movieClipTarget:MovieClip;
// Constructor Method
public function SimpleSquare( x:Number, y:Number, size:Number,
target:MovieClip) {
coords = new Object();
coords.x = x;
coords.y = y;
this.size = size;
movieClipTarget = target;
var depth:Number = movieClipTarget.getNextHighestDepth();
name = "mySquare_" + depth;
mc = movieClipTarget.createEmptyMovieClip(name, depth);
mc._x = coords.x;
mc._y = coords.y;
}
//draw method
public function draw():Void {
mc.beginFill( 0x0022CC, 80 );
mc.lineStyle( 2, 0xFF9900, 100 );
mc.moveTo( 0, 0 );
mc.lineTo( size, 0 );
mc.lineTo( size, size );
mc.lineTo( 0, size );
mc.lineTo( 0, 0 );
mc.endFill();
}
}

