Skip to content

Instantly share code, notes, and snippets.

@dackdel
Created February 27, 2013 20:52
Show Gist options
  • Save dackdel/5051610 to your computer and use it in GitHub Desktop.
Save dackdel/5051610 to your computer and use it in GitHub Desktop.
angle between vectors
float x, y;
PFont font;
void setup() {
size (400, 400);
background(255);
smooth();
font = createFont("Arial", 12, true);
x = random(width);
y = random (height);
}
void draw() {
fill(255);
noStroke();
rect(0, 0, width, height);
stroke(0);
float centerX = width/2;
float centerY = height/2;
ellipse(x, y, 4, 4);
ellipse(mouseX, mouseY, 6, 6);
float slope = slopeFunct(centerX, centerY, mouseX, mouseY);
float theta = angle(centerX, centerY, mouseX, mouseY);
float slope1 = slopeFunct(centerX, centerY, x, y);
float theta1 = angle(centerX, centerY, x, y);
float diff = (theta - theta1);
textFont(font);
fill(0);
text("Angle 1 = " + theta, 10, 40);
text("Angle 2 = " + theta1, 10, 60);
text("Separation = " + diff, 10, 80);
} // End Draw.
// Functions:
float slopeFunct(float x1, float y1, float x2, float y2) {
line (x1, y1, x2, y2);
float dx = x2 - x1;
float dy = y2 - y1;
return dy/dx;
}
float angle(float x1, float y1, float x2, float y2) {
float angle;
float dx = x2 - x1;
float dy = y2 - y1;
float slope = dy/dx;
if (dx >= 0 && dy >= 0) {
angle = degrees(atan(slope));
}
else if (dx < 0 && dy > 0) {
angle = degrees(atan(slope)) + 180;
}
else if (dx < 0 && dy <= 0) {
angle = degrees(atan(slope)) + 180;
}
else if (dx >=0 && dy < 0) {
angle = degrees(atan(slope)) + 360;
}
else angle = 1000;
return angle;
}
void mousePressed() {
setup();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment