Hello,
This time some simple drawing in a really short post. I’ve needed this functionality for my next post (I’m finishing a 3d-html-rotator -and creating polygons is crucial for positioning the elements in a 3d environment).
What it does?
Draws a regular convex polygon using specified parameters (radius,number of sides,x,y).
drawPoly(30,6,50,50); // draws a 30px radius hexagon positioned on x:50,y:50px
The code (AS3):
//some vars
var poly_id,ratio,top,coords;
//the main function drawPoly(radius,segments,center x, center y);
function drawPoly(r:int,seg:int,cx:Number,cy:Number):void
{
poly_id=0; //->0
coords=new Array(); //->0
ratio=360/seg; //calculated ratio/step
top=cy-r; //top
for(var i:int=0;i<=360;i+=ratio) //the main loop- ratio used here
{
var px:Number=cx+Math.sin(radians(i))*r; // point X
var py:Number=top+(r-Math.cos(radians(i))*r); // point Y
coords[poly_id]=new Array(px,py); //2nd level array
if(poly_id>=1)
{
poly_draw(coords[poly_id-1][0],coords[poly_id-1][1],coords[poly_id][0],coords[poly_id][1]); //drawing here
}
poly_id++; // increment for the id
}
poly_id=0; //id->0
};
//degrees2radians
function radians(n:Number):Number
{
return(Math.PI/180*n);
};
//the drawing function – you can draw anything you want here – in this case it connects the points with red lines
function poly_draw(sx:Number,sy:Number,ex:Number,ey:Number):void
{
graphics.lineStyle(1,0xFF0000,1);
graphics.moveTo(sx,sy);
graphics.lineTo(ex,ey);
};
// example usage
drawPoly(30,6,50,50); //hexagon
drawPoly(30,3,150,50); //triangle
drawPoly(30,4,250,50); //square
drawPoly(30,8,350,50); //octagon
drawPoly(30,64,450,50); //almost a circle;-)
The .fla file – here.
Have fun,
FLAIM













June 14, 2008 at 8:35 pm
Excelent code!!! Question: Who its possible to FILL polygons?
February 4, 2009 at 2:42 pm
Hi Joao,
You have to replace the graphics.moveTo(sx,sy); with the lineTo method (because moveTo doesn’t create a closed polygon) – of course add graphics.beginFill( … before the shape is drawn…
Cheers,
FLAIM
June 8, 2009 at 3:59 am
this came handy on a hex tile project i’m working on.
thanks FLAIM.