Last active
June 26, 2020 02:00
-
-
Save OthmanT/22e2f0b99b0f594ed20433ec5fbd328f to your computer and use it in GitHub Desktop.
How to check if a point is in an arc.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Arc arc; | |
void setup() { | |
size(500, 500); | |
arc = new Arc(width/2, height/2, -PI, PI/4, 200); | |
} | |
void draw() { | |
background(51); | |
arc.rotateBy(0.03); | |
arc.display(); | |
if (arc.containsPoint(mouseX, mouseY)) { | |
fill(0, 255, 0); | |
} else { | |
fill(255, 0, 0); | |
} | |
noStroke(); | |
circle(mouseX, mouseY, 10); | |
} | |
class Arc { | |
float radius; | |
float startingAngle; | |
float endingAngle; | |
float centerX; | |
float centerY; | |
Arc(float x, float y, float startingAngle, float endingAngle, float radius) { | |
this.centerX = x; | |
this.centerY = y; | |
this.startingAngle = startingAngle; | |
this.endingAngle = endingAngle; | |
this.radius = radius; | |
} | |
void rotateBy(float angle) { | |
startingAngle += angle; | |
endingAngle +=angle; | |
} | |
boolean containsPoint(float x, float y) { | |
float r = sqrt( pow((x - centerX), 2) + pow((y - centerY), 2)); | |
float a = atan2(y - centerY, x - centerX) + PI;//+PI to shift to a standard circle | |
//Convert the angle to a standard trigonometric circle | |
float s = (startingAngle + PI)%TWO_PI; | |
float e = (endingAngle + PI)%TWO_PI; | |
//Inspired by | |
//https://stackoverflow.com/questions/6270785/how-to-determine-whether-a-point-x-y-is-contained-within-an-arc-section-of-a-c | |
if (r < radius) { | |
if (s < e) { | |
if (a > s && a < e) { | |
return true; | |
} | |
} | |
if (s > e) { | |
if (a > s || a < e) { | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
void display() { | |
noFill(); | |
stroke(255); | |
strokeWeight(2); | |
arc(centerX, centerY, radius*2, radius*2, startingAngle, endingAngle, PIE); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment