- Home /
How can i calculate angle ?
in 2D space how can i calculate angle which between 2 vector?
Answer by Bunny83 · Aug 15, 2015 at 09:21 AM
Unity already has a method that calculates the angle between two vectors (Vector2.Angle). An alternative is to calculate the dot product between the two directions. If both vectors are normalized the result is the cosine of your angle:
Vector2 forward;
Vector2 vector1;
Vector2 vector2;
Vector2 dir = vector2 - vector1;
// first solution
float angle = Vector2.Angle(forward, dir);
// second solution
float angle = Mathf.Acos(Vector2.Dot(forward.normalized, dir.normalized));
Keep in mind that the angle is always positive. If you need an angle based on the orientation of the two vectors you have to determine the order of the two direction vectors. The cross product is the easiest way:
Vector tmp = Vector3.Cross(forward, dir);
if (tmp.z > 0)
// dir is above forward
else
// dir is below forward
That's all ^^.
Thank you so much, that was super usefull for a project I'm doing.
super good example thanks! I was just wondering how to use the cross product to check the rotation direction.
Actually Unity now has a SignedAngle method that does this internally and returns an angle between -180 and 180. You just have to provide a reference axis which is used to deter$$anonymous$$e the sign. For 2d you would just use Vector3.forward as axis.
Answer by JoshuaStrunk · Aug 15, 2015 at 04:32 AM
Trig. This method only works if when you refer to forward you actually mean the Vector2.right or equivalent Vector3.right. In other words the angle between a vector and the positive x-axis
If you start at Vec1, and Vec2 is the direction you want the angle first
//First you have to translate you Vec2 to be a direction vector in world space
//You can do this by subtracting its start point from its end point.
Vector2 vecD= vec2 - vec1;
//This will get you the answer in radians
float b = Mathf.Acos( vecD.x/ vecD.magnitude);
//This converts to degrees
float bDegrees = Mathf.Deg2Rad * b;
//Optional if you want your angles going below the X-axis to be negative
//This only really makes sense when working in degrees
if(vecD.y <0) {
float bDegrees -= 360;
}
Uhm, that doesn't make much sense in this case. First of all we don't have a right triangle. For an arbitrary triangle you would have to use the "Law of cosines". However using the dot product is actually much simpler.
You were 100 percent correct I have gone ahead and updated to correct my answer for when forward is actually the positive x-axis.
Your answer
Follow this Question
Related Questions
Angles invert after flipping player by 180 on Y-axis in 2D. 0 Answers
Getting x and y from an angle. (Unity 2D) 1 Answer
How to calculate angle in the triangle formed by screen touches 1 Answer
Is there anyway i can get the scene back????? 0 Answers
URP lighting 2d not working on Android,URP 2D lighting not working on Android 0 Answers