- Home /
Vector2.angle - how do i get if it's CW or CCW ?
is there any way to get angle between 2 vectors where i get N for clockwise -N for counterclockwise? or any other way how to get this info?
Answer by ArkaneX · Apr 02, 2014 at 01:59 PM
Basing on answer to this StackOverflow question, you can also use:
private static float GetAngle(Vector2 v1, Vector2 v2)
{
var sign = Mathf.Sign(v1.x * v2.y - v1.y * v2.x);
return Vector2.Angle(v1, v2) * sign;
}
This is the standard cross-product trick. The direction of the cross product tells you + or - angle. Since both are "flat" 2D vectors, you know the cross product is either pointing straight up or straight down -- Z is +1 or -1 -- and x and y are 0. That line computes the Z component of cross product.
Think it should be "times negative sign." Try it with up and east: (0,1) and (1,0). Result should be +90. But the math gives 0-1. Then try flipped with East to Up -- (1,0) and (0,1). Result should be -90. $$anonymous$$ath gives 1-0 this time. It's backwards since real math thinks a positive angle is CCW.
It's backwards since real math thinks a positive angle is CCW.
Assu$$anonymous$$g we use left handed coordinate system.
Answer by Xare · Apr 02, 2014 at 12:24 PM
it's always the smallest angle between the two points so it never returns something bigger than 180degrees.
What you can do is to get a static third point and calculate the angles between the 1st and 3rd point and then 2nd and 3rd point and then compare the values to see the angle between the 1st and 2nd points.
Answer by VesuvianPrime · Apr 02, 2014 at 12:08 PM
There's probably a better way, but off the top of my head:
Rotate both Vector2s such that the start vector points up
Check if the x component of the second vector is greater or smaller than the x component of the first vector.
Answer by whydoidoit · Apr 02, 2014 at 12:15 PM
This will do it for Vector2s if you leave n as the default
public static float AngleSigned(Vector3 v1, Vector3 v2, Vector3 n = default(Vector3))
{
n = n == default(Vector3) ? Vector3.forward : n;
return Mathf.Atan2(Vector3.Dot(n, Vector3.Cross(v1, v2)), Vector3.Dot(v1, v2))*Mathf.Rad2Deg;
}
Answer by joaoborks · Jul 13, 2017 at 04:56 PM
Now done natively: https://docs.unity3d.com/ScriptReference/Vector3.SignedAngle.html