Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angle between two lines is wrong

I want to get angles between two line. 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 it doesn't work . The Log is that: 146.309935 -2.553590

What's the matter? I can't know the reason. Please help me.

enter image description here

like image 261
bTagTiger Avatar asked Sep 14 '11 14:09

bTagTiger


People also ask

Can the angle between two lines be negative?

An angle between 2 lines can never be greater than 180° or less than 0°.

What is the angle between two lines?

The angle between two lines can be calculated from the slopes of the lines or from the equation of the two lines. The simplest formula to find the angle between the two lines is from the slope of the two lines. The angle between two lines with slopes m1 m 1 , and m2 m 2 respectively is Tanθ = m1−m21+m1.

What is the angle between the lines 2x 3y =- Z and 6x =- Y =- 4z?

Therefore, the angle between the lines 2x = 3y = – z and 6x = -y = -4z is 90∘.


3 Answers

If you simply use

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

you'll get the angle with the horizontal line y=posY (blue angle).

enter image description here

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

like image 57
Manlio Avatar answered Oct 11 '22 22:10

Manlio


Here's a function I use. 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 I found out you can just use atan2(y,x). Most compiler libraries have this function. You can ignore my function above.

like image 27
Mike Lorenz Avatar answered Oct 11 '22 21:10

Mike Lorenz


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

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 specify point on one of the lines, intersection point and point on the other line.

like image 42
Rafa de King Avatar answered Oct 11 '22 20:10

Rafa de King