Skip to content

Instantly share code, notes, and snippets.

@jbcrail
Created August 22, 2012 21:28
Show Gist options
  • Save jbcrail/3429550 to your computer and use it in GitHub Desktop.
Save jbcrail/3429550 to your computer and use it in GitHub Desktop.
Flexible Triangle
PVector[] v = new PVector[3];
int HOVER_DIAMETER = 15;
int ARC_DIAMETER = 20;
int selectedVertex = -1;
boolean draggingVertex = false;
void setup() {
size(600, 600);
smooth();
cursor(CROSS);
v[0] = new PVector(200, 200);
v[1] = PVector.add(v[0], new PVector(100, -100));
v[2] = PVector.add(v[1], new PVector(100, 100));
}
void draw() {
background(255, 255, 255);
for(int i=0; i < 3; i++) {
drawLine(i);
drawArc(i);
checkForHover(i);
}
if (selectedVertex > -1) {
if (draggingVertex) {
fill(255, 0, 0);
} else {
fill(0, 102, 153);
}
text(nfs(selectedVertex, 1), 15, 60);
}
}
void mousePressed() {
selectedVertex = -1;
for(int i=0; i < 3; i++) {
if (hover(i)) {
selectedVertex = i;
}
}
}
void mouseDragged() {
if (selectedVertex > -1) {
draggingVertex = true;
v[selectedVertex].x = mouseX;
v[selectedVertex].y = mouseY;
}
}
void mouseReleased() {
draggingVertex = false;
selectedVertex = -1;
}
void drawLine(int i) {
line(v[i].x, v[i].y, v[(i+1)%3].x, v[(i+1)%3].y);
}
// If return value is greater than 0, c is left of line (a,b)
// If return value is less than 0, c is right of line (a,b)
// If return value is 0, then c is colinear with line (a,b)
float crossProduct(PVector a, PVector b, PVector c) {
return (b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x);
}
void drawArc(int i) {
PVector v1 = PVector.sub(v[(i+1)%3],v[i]);
PVector v2 = PVector.sub(v[(i+2)%3],v[i]);
noFill();
if (crossProduct(v[i], v[(i+1)%3], v[(i+2)%3]) >= 0) {
arc(v[i].x, v[i].y, ARC_DIAMETER, ARC_DIAMETER, v1.heading2D(), v1.heading2D() + PVector.angleBetween(v1, v2));
} else {
arc(v[i].x, v[i].y, ARC_DIAMETER, ARC_DIAMETER, v2.heading2D(), v2.heading2D() + PVector.angleBetween(v1, v2));
}
}
void checkForHover(int i) {
if (hover(i) == false) return;
fill(0, 102, 153);
PVector v1 = PVector.sub(v[(i+1)%3],v[i]);
PVector v2 = PVector.sub(v[(i+2)%3],v[i]);
text(nfs(degrees(PVector.angleBetween(v2, v1)), 1, 2), 15, 30);
fill(color(255, 0, 0), 128);
ellipse(v[i].x, v[i].y, HOVER_DIAMETER, HOVER_DIAMETER);
}
boolean hover(int i) {
float distX = v[i].x - mouseX;
float distY = v[i].y - mouseY;
return sqrt(sq(distX) + sq(distY)) < HOVER_DIAMETER/2;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment