两个矢量2D之间的角度

时间:2012-11-19 17:27:21

标签: c# vector xna

我正在尝试计算两个向量之间的角度。 我尝试了这个,但它总是返回零:

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));

Vectors The angle I need

8 个答案:

答案 0 :(得分:18)

您应该查看atan2here)的文档。

您正在寻找的是找到B(左上角矢量)和A(右下角矢量)之间的差异,然后将其作为参数传递给atan2

return Math.Atan2(b.Y - a.Y,b.X - a.X);

您的代码目前所做的是在引用b时找到向量0,0的角度,并在引用a时减去向量0,0的角度。< / p>

你总是得到0的原因是因为1,150,50位于跨越0,0的同一行(两个调用都返回大约0.785398),所以减去它们将导致0

答案 1 :(得分:4)

我认为代码显示如下来自.NET源代码的副本可以帮助你。

参考: 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);
}

答案 2 :(得分:1)

你必须使用Atan2方法中x和y的差异:

Math.Atan2(b.Y - a.Y,b.X - a.X);

另外,我相信这会给你从0到你提供的三角形斜边的角度(不完全确定)。

我建议您尝试Math.PI - angle

答案 3 :(得分:1)

一个简单的解决方案应该是:

Vector2 a_normalized = normalize(a);
Vector2 b_normalized = normalize(b);
double angle = arccos(dot(a_normalized,b_normalized));

http://simple.wikipedia.org/wiki/Dot_product

这是伪代码,因为C#不是我的世界。遗憾

答案 4 :(得分:1)

如果要查找“矢量a和b之间的角度”,则需要矢量a的角度增量和矢量b的角度:

Math.Atan2(b.Y, b.X) - Math.Atan2(a.Y, a.X)

但该图与“矢量之间的角度”不匹配。该图的答案确实是先前给出的答案:

Math.Atan2(b.Y - a.Y, b.X - a.X)

答案 5 :(得分:1)

我参加派对有点晚了,但是Vector类上的静态方法怎么样:

Vector.AngleBetween(vector1, vector2)

答案 6 :(得分:0)

tan(角度)=相反/相邻

arctan(对面/相邻)=角度

对面= a.y - b.y

adjascent = b.x - a.x

Math.Atan((a.Y - b.Y) / (b.X - a.X));

答案 7 :(得分:0)

因为你使用了vector2类,我想你可以使用

A-B

从a到b获取向量。

所以你需要的角度是:Pi - 角度(a-b)。