开发者

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 radi开发者_Go百科ans, 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.

Angle between two lines is wrong


If you simply use

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

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

Angle between two lines is wrong

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜