Absolute angle between lines using inverse cosine

I want to calculate the angle between two lines formed by three points (one of the points is the intersection point of the two lines) using the inverse cosine function as follows:

CGFloat a = initialPosition.x - origin.x; CGFloat b = initialPosition.y - origin.y; CGFloat c = currentPosition.x - origin.x; CGFloat d = currentPosition.y - origin.y; CGFloat angle = (180/M_PI) * acosf(((a*c) + (b*d)) / ((sqrt(a*a + b*b)) * (sqrt(c*c + d*d)))); 

Unfortunately, acosf only returns a value from 0 to pi. How to find a value between 0 and 2 * pi (e.g. clockwise)?

+4
source share
2 answers

I don’t know what language you use, but usually there is an atan2 function that gives you a full 360 degree value. in this case you need to use it twice and then add a little extra logic.

some pseudo code will help clear things up:

 initialAngle = atan2(initialPosition.y - origin.y, initialPosition.x - origin.x) currentAngle = atan2(currentPosition.y - origin.y, currentPosition.x - origin.x) # angle is measured from x axis anti-clock, so lets find the value starting from # initial and rotating anti-clock to current, as a positive number # so we want current to be larger than initial if (currentAngle < initialAngle) {currentAngle += 2 pi} # and then we can subtract return currentAngle - initialAngle 

I know that this is not using acos, but it is ambiguous, so doing this ends up using a lot of logic about the signs of differences that are error prone. atan2 is what you want.

+6
source

found a simple solution ... It comes from high school math! First make the equation of the line made from the origin and the initial position of the form y = mx+c . A point lying on either side of this line will satisfy y < mx+c or y > mx+c , depending on where it is located. If you find the angles clockwise or counterclockwise, do the following check:

 currentPosition.y < (currentPosition.x *(initialPosition.y - origin.y) + (initialPosition .x * origin.y - initialPosition.y * origin.x)) / (initialPosition.x - origin.x) 

If the above condition is true, then the line formed from the beginning and the current position makes an angle less than 180 degrees (clockwise) with the line formed from the beginning and the starting position. Otherwise, the tilt angle is more than 180 degrees clockwise and less than 180 degrees counterclockwise ... and so on. Depending on the requirement, the final angle is either (angle returned by acos) or (360 - (angle returned by acos)) .

+2
source

All Articles