Instantly share code, notes, and snippets.

# suzukimilanpaak/draw_equilateral_polygon.pde Last active Jan 2, 2016

Draw a Equilateral Polygon according to the number of vertexes in Processing language 2.1
 // Size of display int DISPLAY_WIDTH = 500; int DISPLAY_HEIGHT = 500; // Colours int BLACK = 0; int WHITE = 255; int CENTER_X = 0; int CENTER_Y = 0; EquilateralPolygon polygon; // This class saves coordinate class Coordinate { int x; int y; // The Constructor is defined with arguments. Coordinate(float _x, float _y) { x = int(_x); y = int(_y); } public String toString() { return x + ", " + y; } } class EquilateralPolygon { int numVertexes; int radius; float[] angles; Coordinate[] vertexes; EquilateralPolygon(int _numVertexes, int _radius) { numVertexes = _numVertexes; angles = new float[numVertexes]; radius = _radius; } public float xVertex(int i, int extra) { return cos(angles[i]) * (radius + extra); } public float yVertex(int i, int extra) { return sin(angles[i]) * (radius + extra); } public Coordinate[] vertexes() { vertexes = new Coordinate[numVertexes]; float angleForSingleArc = 2 * PI / numVertexes; for(int i = 0; i < numVertexes; i++) { // Sum up angles angles[i] = HALF_PI - angleForSingleArc * i; float x = xVertex(i, 0); float y = - yVertex(i, 0); vertexes[i] = new Coordinate(x, y); } return vertexes; } // Put tiny circles onto each vertex public void drawVertexes() { smooth(); textAlign(CENTER); int r = 20; for (int i = 0; i < numVertexes; i++) { // Draw black circle for the first vertex and draw gray ones for the rest int colorValue = i == 0 ? 0 : 200; stroke(colorValue); strokeWeight(1); ellipse(vertexes[i].x, vertexes[i].y, r, r); } } public void drawIndexes() { for (int i = 0; i < numVertexes; i++) { fill(BLACK); text(i, vertexes[i].x, vertexes[i].y); noFill(); } } } void setup() { size(DISPLAY_WIDTH, DISPLAY_HEIGHT); background(WHITE); noLoop(); } void draw() { // Displace the drawn polygon by half width and half height of `display`, which means center. // With `translate`, we can calculate coodinate of each vertex as distance from the center of a // diagram, where it's coordinate is as (0, 0), and then, displace the polygon to actual coordinate // of `display`. translate(DISPLAY_WIDTH / 2, DISPLAY_HEIGHT / 2); polygon = new EquilateralPolygon(6, 200); polygon.vertexes(); polygon.drawVertexes(); polygon.drawIndexes(); saveFrame("result.jpg"); }