I have three vector points where i want to get the angle of one of the vertices. I tried to use the law of cosines - cos C = (a² + b² - c²)/2ab, but i get non accurate results.Here is my GetAngle() method
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;
}
Given that i insert the three vectors:
vec1 = new Vector2(1,1);
vec2 = new Vector2(1,5);
vec3 = new Vector2(5,5);
Where i want to find the angle of vec3 respectively:
Result: NaN, then when i start moving the vectors i get sometimes inverted angles sometimes again NaN.Its hard to me to observe and inspect what is happening but i was thinking did i get the formula and coding right?
Edit: Observing more when i move vec1 to position (1,5) i get 90 degrees, further to position (1,10) i get 40 degrees..
Yes thanks to Rawling i successfully implemented the method: Here is the code:
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;
}
works like a charm now..
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.