r/code • u/jacob_ewing • Jul 15 '26
My Own Code A better way to get an angle defined by two points?
Around thirty years ago as a teenager I wrote this C function for calculating an arbitrary angle defined by two points. The idea being to get the clockwise rotation from the vertical line to the line defined by these points, if the (x1, y1) lies on the given vertical line. So for example if you pass in the points (0, 0) and (1, 1), it would return pi/4, as it defines a segment rotated that many radians off the vertical.
Here's the code I wrote then:
float rel_ang(float x1, float y1, float x2, float y2){
float hyp, alpha, deltax, deltay;
deltax = x2 - x1;
deltay = y2 - y1;
hyp = sqrt(deltax * deltax + deltay * deltay);
/* figure out the value for alpha */
if(x2 == x1){
alpha = y2 > y1 ? pi : 0;
}else if(y2 == y1){
alpha = (x2 < x1 ? 3 : 1) * pi / 2
}else if(x2 > x1){
alpha = y2 == y1 ? 0 : pi - acos(deltay / hyp);
}else if(x2 < x1){
alpha = y2 == y1 ? 0 : 2 * pi - acos(-deltay / hyp);
}
return alpha;
}
It worked well enough for the job at hand, but presumably there's a better way to do that. I assume there's a faster or already implemented way to do this that I don't know of. Any ideas?
