Here are a few functions I find myself using constantly lately. Maybe it can be useful to someone.
//gets the angle of a point
float getAngle(float _x, float _y) {
if (_x == 0.0) {
if(_y < 0.0)
return 270;
else
return 90;
} else if (_y == 0) {
if(_x < 0)
return 180;
else
return 0;
}
if ( _y > 0.0)
if (_x > 0.0)
return atan(_y/_x) * GRAD_PI;
else
return 180.0 - (atan(_y/-_x) * GRAD_PI);
else
if (_x > 0.0)
return 360.0 - (atan(-_y/_x) * GRAD_PI);
else
return 180.0 + (atan(-_y/-_x) * GRAD_PI);
}
//rotates point (start) around origin using angle
this one took me alot of googling to figure out
ofxVec2f rotatePoint(ofxVec2f start, ofxVec2f origin, float angle) {
/*
a counterclockwise rotation of a coordinate or vector about the origin,
where (x,y) is rotated θ and we want to know the coordinates after the rotation, (x',y'):
x' = x cos θ - y sin θ
y' = x sin θ + y cos θ
we need to subtract the center point, do our math and then add it in order to get the
coordinates around a point of origin or else we would get the coordinates around origin (0,0)*/
ofxVec2f result;
result.x = (cos(angle*PI/180.0) * (start.x - origin.x) - sin(angle*PI/180.0) * (start.y - origin.y)) + origin.x;
result.y = (cos(angle*PI/180.0) * (start.y - origin.y) + sin(angle*PI/180.0) * (start.x - origin.x)) + origin.y;
return result;
}
//returns true if point p is inside polygon (N is the number of corners)
I usually use another version I did using vector and I get the N using vector.size() but this is the base I started with
http://local.wasp.uwa.edu.au/~pbourke/g-…-nsidepoly/
bool InsidePolygon(ofPoint *polygon, int N, ofPoint p)
{
int counter = 0;
int i;
double xinters;
ofPoint p1,p2;
p1 = polygon[0];
for (i=1;i<=N;i++) {
p2 = polygon[i % N];
if (p.y > MIN(p1.y,p2.y)) {
if (p.y <= MAX(p1.y,p2.y)) {
if (p.x <= MAX(p1.x,p2.x)) {
if (p1.y != p2.y) {
xinters = (p.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x;
if (p1.x == p2.x || p.x <= xinters)
counter++;
}
}
}
}
p1 = p2;
}
if (counter % 2 == 0) return false;
else return true;
}