2011-09-14 102 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; 
} 

這會爲你工作,如果你對一個指定點在另一條線上的線,交點和點。