Search code examples
geometryatan2

algorithm of calculating the slope between line relatively to center coordinate


Please help with the algorithm of calculating the slope So we have a Cartesian coordinate system. X right at Y the top. There is a line which passes through the center of coordinates. Needed to determine the angle relatively to the axis OX.

So here's what I'm doing

  1. Certain functions transferred to the origin (top line) and end of line
  2. Determine dx, dy
  3. Hildren releases two parameters in atan2 (dy, dx)
  4. Returns the result in radians.

But! I atan2 works only within 180 degrees. After 180 goes in another direction.

So the question: what is the correct algorithm for finding the angle? Do I need to take dy, dx values in magnitude? How to make the arctangent calculated for all 360 and more? I would be glad to hear specific algorithms, or pieces of code comments. Thanx!

static inline CGFloat angleBetweenLinesInRadians2 (CGPoint line1Start, CGPoint line1End)
{
CGFloat dx = 0, dy = 0;

dx = line1End.x - line1Start.x; / / whether to do fabs (line1End.x - line1Start.x);
dy = line1End.y - line1Start.y;

CGFloat rads = atan2 (dy, dx); / / whether to do fabs (rads)

return rads;
}

Solution

  • atan2() is supposed to return a value in the interval [-pi,pi] (i.e. [-180, 180] ), and works with the signs of x and y to figure out the quadrant. (C++ ref)

    So technically, you have 360 degrees.