05 February 2010

ActionScript3.0 Triangle Class

Next two posts are my continuing effort to understand drawing AS3.0 API. Before reading this one you might be interested in previous posts:

- Visual rectangles intersection AS3 example
- Understanding shearing using Matrix object
- Curves and fill with AS3 drawing API
- AS3 drawing API examples


This post will introduce custom ActionScript3.0 Triangle class and next post will show you how to use it with Pyramide class to draw a pyramid using one Point and pyramid height as only parameters. Triangle class is very simple. It uses 3 Point parameters and one Boolean parameter.



public function Triangle(a:Point, b:Point, c:Point, d:Boolean)

Parameter d acts as flag, if you make it TRUE triangle will be drawn on stage with predefined color using 3 Point parameters, but if you make it FALSE, triangle will be crated but it will not appear on the stage right away. This option is added if you want to change triangle color before adding it visually. Now, here is Triangle.as


package com.blogspot.flanture.triangles
{
import flash.geom.Point;
import flash.display.Sprite;

public class Triangle extends Sprite
{
private var _a:Point;
private var _b:Point;
private var _c:Point;
private var _draw:Boolean;
private var _color:uint = 0x0000ff;

public function set color(newcolor:uint):void
{
_color = newcolor;
}
public function get color():uint
{
return _color;
}
public function set draw(newdraw:Boolean):void
{
_draw = newdraw;
}
public function get draw():Boolean
{
return _draw;
}

public function Triangle(a:Point, b:Point, c:Point, d:Boolean)
{
_a = a;
_b = b;
_c = c;
_draw = d;

// draw it if required
if(_draw) {
drawIt();
}

}

public function drawIt():void
{
this.graphics.clear();
this.graphics.lineStyle(1);
this.graphics.beginFill(_color);
this.graphics.moveTo(_a.x, _a.y);
this.graphics.lineTo(_b.x, _b.y);
this.graphics.lineTo(_c.x, _c.y);
this.graphics.lineTo(_a.x, _a.y);
this.graphics.endFill();
}
}
}

Now we need some example to see if it works OK. Create new document and enter next code:


import com.blogspot.flanture.triangles.Triangle;

for (var i:uint=0; i<20; i++) {
var t:Triangle = new Triangle(grp(), grp(), grp(), true)
addChild(t);
}

// get random Point
function grp():Point {
var xp:Number = Math.random()*stage.stageWidth;
var yp:Number = Math.random()*stage.stageHeight;
return new Point(xp, yp);
}

You will get 20 random position blue triangles on stage. If you want to change color, before addChild() method put t.color = newcolor; where newcolor is 0x000000 format.


*_*

2 comments:

Gilbert said...

You should check the drawTriangles method, which is one of the major additions to the Graphics API in Flash Player 10.

Check http://livedocs.adobe.com/flex/3/langref/flash/display/Graphics.html#drawTriangles%28%29

With it you can do all sort of interesting things, such as http://www.boostworthy.com/blog/?p=242

flanture said...

thanks Gilbert

 

template by blogger templates