2014-03-31 110 views
0

我有三個矢量點,我想要得到其中一個頂點的角度。 我試圖用餘弦定理 - COS C =(A²+稱b² - C²)/ 2AB,但我得到的非精確results.Here是我GetAngle()方法三個矢量點之間的角度

public static float GetAngle(Vector2 vec1, Vector2 vec2, Vector2 vec3) 
{ 
    float lenghtA = Mathf.Sqrt(vec1.x * vec1.x + vec1.y * vec1.y); 
    float lenghtB = Mathf.Sqrt(vec2.x * vec2.x + vec2.y * vec2.y); 
    float lenghtC = Mathf.Sqrt(vec3.x * vec3.x + vec3.y * vec3.y); 

    float calc = ((lenghtA * lenghtA) + (lenghtB * lenghtB) - (lenghtC * lenghtC))/(2 * lenghtA * lenghtB); 

    return Mathf.Acos(calc) * Mathf.Rad2Deg; 
} 

鑑於我插入三載體:

vec1 = new Vector2(1,1); 
vec2 = new Vector2(1,5); 
vec3 = new Vector2(5,5); 

,我想分別找到VEC3的角度:

結果:NaN,那麼當我開始再次有時我感動有時得到倒角度矢量NaN.Its硬給我觀察並檢查發生了什麼,但我想我是否得到了公式和編碼權?

編輯:觀察更當我移動到VEC 1位置(1,5)我得到90度,進一步位置(1,10)我得到40度..

+0

在餘弦定理長度是三角形的邊緣的長度,但你計算每個的距離從起點開始的三角形的點。 – Rawling

+0

所以我的猜測是我必須:lenghtA =(vec3.x - vec2.x,vec3.y - vec2.y) –

+1

是的,只需要小心三個減法,你會最終與你對待正確的A,B和C! – Rawling

回答

0

是由於Rawling我順利實施方法: 以下是代碼:

public static float GetAngle(Vector2 vec1, Vector2 vec2, Vector2 vec3) 
    { 
     float lenghtA = Mathf.Sqrt(Mathf.Pow(vec2.x - vec1.x, 2) + Mathf.Pow(vec2.y - vec1.y,2)); 
     float lenghtB = Mathf.Sqrt(Mathf.Pow(vec3.x - vec2.x,2) + Mathf.Pow(vec3.y - vec2.y, 2)); 
     float lenghtC = Mathf.Sqrt(Mathf.Pow(vec3.x - vec1.x,2) + Mathf.Pow(vec3.y - vec1.y, 2)); 

     float calc = ((lenghtA * lenghtA) + (lenghtB * lenghtB) - (lenghtC * lenghtC))/(2 * lenghtA * lenghtB); 

     return Mathf.Acos(calc) * Mathf.Rad2Deg; 

    } 

作品像現在一個魅力..