Skip to content

Instantly share code, notes, and snippets.

@josePhoenix
Created March 27, 2014 05:09
Show Gist options
  • Save josePhoenix/9800744 to your computer and use it in GitHub Desktop.
Save josePhoenix/9800744 to your computer and use it in GitHub Desktop.
/*
*
* Arbitrary Polygons with tfpractice
*
*/
class Polygon {
float x, y;
int numSides;
float r;
float baseAngle;
PVector[] vertices;
Polygon(float _x, float _y, int _numSides, float _r) {
x = _x;
y = _y;
numSides = _numSides;
r = _r;
baseAngle = TWO_PI / numSides;
vertices = new PVector[_numSides];
// jdl: call this in the constructor so we never
// have a Polygon with uninitialized vertices
establishVertices();
}
void establishVertices() {
for (int i=0; i<numSides; i++) {
// jdl: from the PVector reference page, we can create a new
// unit vector at some angle (setting both x and y in one step)
vertices[i] = PVector.fromAngle(baseAngle * i);
// jdl: then we scale it (multiply by scalar) to the radius of the polygon
vertices[i].mult(r);
}
}
void display() {
beginShape(); // jdl: must be OUTSIDE the loop
for (int i=0; i<numSides; i++) {
// jdl: I might change 'x' to 'xCenter' or 'xOffset' for clarity
vertex(x + vertices[i].x, y + vertices[i].y);
}
endShape(CLOSE); // jdl: must be OUTSIDE the loop
}
}
Polygon poly;
void setup() {
size(400, 400);
background(127);
fill(255);
poly = new Polygon(200.0, 200.0, 6, 100.0);
poly.display();
}
void draw() {
poly.display();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment