I'm trying to compute the angle between two vectors. I tried this, but it always returns zero:
public double GetAngle(Vector2 a, Vector2 b)
{
double angle = Math.Atan2(b.Y, b.X) - Math.Atan2(a.Y, a.X);
return angle;
}
GetAngle(new Vector2(1,1), new Vector2(50,50));
The angle between two vectors is the angle between their tails. It can be found either by using the dot product (scalar product) or the cross product (vector product). Note that the angle between two vectors always lie between 0° and 180°.
I think code show as below copy from .NET source code could help you.
reference: http://referencesource.microsoft.com/#WindowsBase/Base/System/Windows/Vector.cs,102
/// <summary>
/// AngleBetween - the angle between 2 vectors
/// </summary>
/// <returns>
/// Returns the the angle in degrees between vector1 and vector2
/// </returns>
/// <param name="vector1"> The first Vector </param>
/// <param name="vector2"> The second Vector </param>
public static double AngleBetween(Vector vector1, Vector vector2)
{
double sin = vector1._x * vector2._y - vector2._x * vector1._y;
double cos = vector1._x * vector2._x + vector1._y * vector2._y;
return Math.Atan2(sin, cos) * (180 / Math.PI);
}
You should take a look at the documentation of atan2
(here).
What you're looking of is finding the difference between B (your upper left vector) and A (your bottom right vector), then pass this as a parameter to atan2
return Math.Atan2(b.Y - a.Y, b.X - a.X);
What your code currently does is find the angle of the vector b
in reference to 0,0
and subtract the angle of the vector a
in reference to 0,0
.
The reason you always get 0 is because 1,1
and 50,50
are on the same line that crosses 0,0
(both calls return something approx. 0.785398
), so subtracting them will result in 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With