Regular nGons. We’ve all wanted to draw them at some time, right? Look no further, seeker of knowledge, I’ve got just what you’re looking for.
The method I’m using is pretty simple.
- Assume we are drawing our nGon with its center at 0,0
- Start with a point at
- for an nGon with n sides
- rotate the point 360/n degrees
- do this n+1 times
- add 360/n degrees each time we iterate
So assume we want a 12 sided nGon. We rotate the first point 30 degrees, the next point 60 degrees, 90 degrees and so on.
For the rotation, I’m using:
x’ = x cos Φ - y sin Φ
y’ = y cos Φ + x sin Φ
Where:
x and y are the original position
x’ and y’ are the new position
Φ is the degree of rotation
And because Flash uses radians instead of degrees, we have to convert from degrees to radians when doing this calculation:
radians = (degrees * Π/180)
Add in an x and y offset to each point to place the polygon in the center of the screen.
Here the code that run the movie:
// Drawing Regular Ngons
// Sean Hyde-Moyer
// April 2007
//
// Initialize variables
xOffset = 350
yOffset = 200
var xArray:Array = new Array();
var yArray:Array = new Array();
vert.text = 5;
radius.text = 120;
this.createEmptyMovieClip("planet_mc", this.getNextHighestDepth());
this.onEnterFrame = function() {
incrementalRot = 0.0
updateFlag = 0
startVerts = Number(vert.text)
ngonRadius = Number(radius.text)
//sanity check user values
if (ngonRadius >180) {
ngonRadius = 180
//radius.text = 180;
}
if (ngonRadius <= 20) {
ngonRadius = 20
//radius.text = 1;
}
if (startVerts >512) {
startVerts = 512
}
if (startVerts <= 3) {
startVerts = 3
}
// If values change, redraw poly
if (oldStartVerts != startVerts ){
updateFlag = 1
}
if (oldngonRadius != ngonRadius) {
updateFlag = 1
}
if (updateFlag == 1) {
degreeRot = 360/startVerts
// Resize the demo circle
circle_mc._height = ngonRadius*2
circle_mc._width = ngonRadius*2
circle_mc._x = xOffset
circle_mc._y = yOffset
// Draw the Ngon
planet_mc.clear()
planet_mc.lineStyle(1, 0xFFFF00, 100, true, "normal", "square", "miter", 3);
planet_mc.moveTo(xOffset,ngonRadius+yOffset);
for (i=0; i<=startVerts; ++i) {
radianRot = (incrementalRot * Math.PI/180)
xArray[i] = ((0*Math.cos(radianRot)) - (ngonRadius*Math.sin(radianRot)))
yArray[i] = ((ngonRadius*Math.cos(radianRot)) - (0*Math.sin(radianRot)))
xArray[i] += xOffset
yArray[i] += yOffset
incrementalRot = incrementalRot + degreeRot
planet_mc.lineTo(xArray[i],yArray[i]);
}
}
oldStartVerts = startVerts
oldngonRadius = ngonRadius
}