2011-09-14 98 views
6

我想获得两条线之间的角度。 所以我用这个代码。两条线之间的角度不对


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); 

但它不工作。 日志是:146.309935 -2.553590

怎么回事? 我不知道原因。 请帮帮我。

enter image description here

+0

垂直线呢,它是垂直的吗? – Ariel

+1

你的公式是错误的 – duedl0r

+1

我不知道'x',''''ScreenWidth'和'ScreenHeight'的值,但这看起来是正确的,除了你正在改变数值的符号。你期待什么结果? – filipe

回答

5

如果单纯使用

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

你会得到与水平线y=posY(蓝角)的角度。

enter image description here

你需要添加M_PI_2到您的弧度值,以得到正确的结果。

+0

请详细解释。 – bTagTiger

+0

我编辑了你的图片。你正在计算蓝色角度而不是红色角度。 – Saphrosit

4

这是我使用的功能。它为我的伟大工程......

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; 
} 

编辑:一些研究,我发现你可以使用atan2(y,x)后。大多数编译器库都有这个功能。你可以忽略我上面的功能。

1

如果你有3个点,要计算它们之间的角度在这里是计算正确的角度值的快速和正确的方法:

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; 
} 

这会为你工作,如果你对一个指定点在另一条线上的线,交点和点。