We are going to create a simple Rectangle class. Our goal is it to draw a Rectangle on stage just by writing:
var myRect:Rectangle = new Rectangle();
myRect.create();
At first we create a new ActionScript file and save it as Rectangle.as. The VisibleObject class from the previous post must be in the same directory. Open the Rectangle.as file and copy the following code in it.
// create a Rectangle class and let it inherit from the VisibleObject class
class Rectangle extends VisibleObject{
// define the width and height properties
private var width:Number;
private var height:Number;
public function Rectangle(){
// set the type of the VisibleObject
type = “Rectangle“;
// set the default width and height
width = 100;
height = 12;
}
// override the create method
public function create():Void{
// call the original create method
super.create();
// draw the rectangle
draw();
}
public function draw():Void{
mc.beginFill(0×000000, 100);
mc.moveTo(0, 0);
mc.lineTo(0, height);
mc.lineTo(width, height);
mc.lineTo(width, 0);
mc.lineTo(0, 0);
mc.endFill();
}
public function clear():Void{
mc.clear();
}
// declare getters and setters
public function setWidth(aWidth:Number):Void{
width = aWidth;
}
public function getWidth():Number{
return width;
}
public function setHeight(aHeight:Number):Void{
height = aHeight;
}
public function getHeight():Number{
return height;
}
public function getBoundingBox():Object{
return {width:width, height:height};
}
}
That’s it. To test whether it works or not create a new fla and write the following code in it.
var myRect:Rectangle = new Rectangle(); myRect.create(); trace(myRect.getMC()); trace(myRect.getWidth()); trace(myRect.getHeight()); trace(myRect.getXPosition()); trace(myRect.getYPosition()); // Output: // _level0.Rectangle_0_mc // 100 // 12 // 0 // 0
If you want to see a bigger and more advanced example click here to download the bunch of code.
Click here to see the class hierarchy.
The zip contains all files shown in the class hierarchy as well as a fla that shows how to use all this.
