Skip to content

Instantly share code, notes, and snippets.

@jaycody
Created June 18, 2016 03:48
Show Gist options
  • Save jaycody/c9cf40f0f818ec17c34cf857f3557cf4 to your computer and use it in GitHub Desktop.
Save jaycody/c9cf40f0f818ec17c34cf857f3557cf4 to your computer and use it in GitHub Desktop.
use Selection Sort to sort all of the vertices according to their relative angle from the center
/*thx shiffman!
http://shiffman.net/general/2011/12/23/night-4-sorting-the-vertices-of-a-polygon/
One solution for solving this problem is to always
sort all of the vertices according to their relative angle from the center.
Let’s say you calculate the center of the polygon as the average location of all vertices.
void mousePressed() {
vertices.add(new PVector(mouseX,mouseY));
}
void draw() {
beginShape();
for (PVector v : vertices) {
vertex(v.x, v.y);
}
endShape(CLOSE);
}
/*
//Let’s say you calculate the center of the polygon as the average location of all vertices.
PVector centroid = new PVector();
for (PVector v : vertices) {
centroid.add(v);
}
centroid.div(vertices.size());
You can then make a vector that points from the center to each vertex
and get its direction (using PVector’s heading2D() method).
for (PVector v : vertices) {
PVector dir = PVector.sub(v, centroid);
float a = dir.heading2D() + PI;
}
*/
/*
Note how we add PI to the angle.
The heading2D() function will return an angle between -PI and PI
and it’ll be easier to sort if we just have an angle between 0 and TWO_PI.
One way to sort an ArrayList is called a Selection Sort.
In the example below, you’ll find a variation of the selection sort.
The code iterates through the ArrayList, finds the element with the highest angle,
removes that element and sticks it at the end of a new ArrayList.
It does this again and again until the original ArrayList is empty.
The result is a new ArrayList in sorted order.
Following is that example which implements all of the above into a class.
If you are looking for an exercise, try allowing the user to move or delete existing vertices.
Also, how you would make a system of these polygons so that the user can draw more than one?
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment