两个矢量2D之间的角度
我正在尝试计算两个向量之间的角度。 我试过这个,但它总是返回零:
public double GetAngle(Vector2 a, Vector2 b) { double angle = Math.Atan2(bY, bX) - Math.Atan2(aY, aX); return angle; } GetAngle(new Vector2(1,1), new Vector2(50,50));
你应该看一下atan2
的文档( 这里 )。
您正在寻找的是找到B(您的左上矢量)和A(您的右下矢量)之间的差异,然后将其作为参数传递给atan2
return Math.Atan2(bY - aY,bX - aX);
你的代码目前所做的是找到参考0,0
的向量b
的角度,并减去参考0,0
的向量a
的角度。
你总是得到0的原因是因为1,1
和50,50
在同一行上交叉0,0
(两个调用都返回大约0.785398
),所以减去它们将导致0
我认为代码显示如下来自.NET源代码的副本可以帮助你。
参考: http : //referencesource.microsoft.com/#WindowsBase/Base/System/Windows/Vector.cs,102
/// /// AngleBetween - the angle between 2 vectors /// /// /// Returns the the angle in degrees between vector1 and vector2 /// /// The first Vector /// The second Vector 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); }
你必须使用Atan2方法中x和y的差异:
Math.Atan2(bY - aY,bX - aX);
另外,我相信这会给你从0
到你提供的三角形斜边的角度(不完全确定)。
我建议尝试Math.PI - angle
。
一个简单的解决方案应该是:
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#不是我的世界。 抱歉
我参加派对有点晚了,但是Vector类上的静态方法怎么样:
Vector.AngleBetween(vector1, vector2)
tan(角度)=反向/相邻
arctan(对角/紧张)=角度
对面= ay – by
adjascent = bx – ax
Math.Atan((aY - bY) / (bX - aX));
既然你使用了vector2类,我想你可以使用
AB
从a到b得到向量。
所以你需要的角度是:Pi – 角度(ab)。
如果您正在寻找“矢量a和b之间的角度”,则需要矢量a的角度增量和矢量b的角度:
Math.Atan2(bY, bX) - Math.Atan2(aY, aX)
但该图与“矢量之间的角度”不匹配。 该图的答案确实是先前给出的答案:
Math.Atan2(bY - aY, bX - aX)