Wrong angle between two lines

I want to get the angles between two lines. So I used this code.


int posX = (ScreenWidth) >> 1; int posY = (ScreenHeight) >> 1; double radians, degrees; radians = atan2f( y - posY , x - posX); degrees = -CC_RADIANS_TO_DEGREES(radians); NSLog(@"%f %f",degrees,radians); 

But that will not work. The magazine is as follows: 146.309935 -2.553590

What happened? I can not know the reason. Please help me.

enter image description here

+6
source share
3 answers

If you just use

 radians = atan2f( y - posY , x - posX); 

you will get an angle with the horizontal line y=posY (blue corner).

enter image description here

You need to add M_PI_2 to your radians value to get the correct result.

+5
source

The function is used here. It works great for me ...

 float cartesianAngle(float x, float y) { float a = atanf(y / (x ? x : 0.0000001)); if (x > 0 && y > 0) a += 0; else if (x < 0 && y > 0) a += M_PI; else if (x < 0 && y < 0) a += M_PI; else if (x > 0 && y < 0) a += M_PI * 2; return a; } 

EDIT: After some research that I found out, you can just use atan2 (y, x) . Most compiler libraries have this feature. You can ignore my function above.

+4
source

If you have 3 points and you want to calculate the angle between them, this is a quick and correct way to calculate the value of the right angle:

 double AngleBetweenThreePoints(CGPoint pointA, CGPoint pointB, CGPoint pointC) { CGFloat a = pointB.x - pointA.x; CGFloat b = pointB.y - pointA.y; CGFloat c = pointB.x - pointC.x; CGFloat d = pointB.y - pointC.y; CGFloat atanA = atan2(a, b); CGFloat atanB = atan2(c, d); return atanB - atanA; } 

This will work for you if you indicate a point on one of the lines, an intersection point, and a point on another line.

+1
source

Source: https://habr.com/ru/post/897322/


All Articles