Regular Polygon

Regular Polygon

What is your favorite? Pentagon? Hexagon? Heptagon? No? What about the icosagon? The polygon() function created for this example is capable of drawing any regular polygon. Try placing different numbers into the polygon() function calls within draw() to explore.

```
void setup() {
size(640, 360);
}

void draw() {
background(102);

pushMatrix();
translate(width*0.2, height*0.5);
rotate(frameCount / 200.0);
polygon(0, 0, 82, 3);  // Triangle
popMatrix();

pushMatrix();
translate(width*0.5, height*0.5);
rotate(frameCount / 50.0);
polygon(0, 0, 80, 20);  // Icosahedron
popMatrix();

pushMatrix();
translate(width*0.8, height*0.5);
rotate(frameCount / -100.0);
polygon(0, 0, 70, 7);  // Heptagon
popMatrix();
}

void polygon(float x, float y, float radius, int npoints) {
float angle = TWO_PI / npoints;
beginShape();
for (float a = 0; a < TWO_PI; a += angle) {
float sx = x + cos(a) * radius;
float sy = y + sin(a) * radius;
vertex(sx, sy);
}
endShape(CLOSE);
}```

Functions Used

size()

Defines the dimension of the display window width and height in units of pixels

vertex()

All shapes are constructed by connecting a series of vertices

pushMatrix()

Pushes the current transformation matrix onto the matrix stack

sin()

Calculates the sine of an angle

popMatrix()

Pops the current transformation matrix off the matrix stack

setup()

The setup() function is run once, when the program starts

beginShape()

Using the beginShape() and endShape() functions allow creating more complex forms

rotate()

Rotates the amount specified by the angle parameter

cos()

Calculates the cosine of an angle

translate()

Specifies an amount to displace objects within the display window

draw()

Called directly after setup(), the draw() function continuously executes the lines of code contained inside its block until the program is stopped or noLoop() is called