你应该查看atan2
的文档(这里)。
你需要做的是找到B(你的左上向量)与A(你的右下向量)之间的差异,然后将其作为参数传递给atan2
函数。
return Math.Atan2(b.Y - a.Y, b.X - a.X);
您当前的代码是找到向量 b 相对于点 0,0 的角度,然后减去向量 a 相对于点 0,0 的角度。始终得到 0 的原因是因为点 1,1 和 50,50 在通过点 0,0 的同一条直线上(两次调用都返回约为 0.785398 的值),所以将它们相减将导致结果为 0。
/// <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);
}
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#不是我的领域。抱歉。
如果你正在寻找“向量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)
我有点晚了,但是关于Vector类的静态方法怎么样:
Vector.AngleBetween(vector1, vector2)
在Atan2方法中,您必须使用x和y的差异:
Math.Atan2(b.Y - a.Y,b.X - a.X);
此外,我认为这将为您提供从0到所提供三角形的斜边的角度(不完全确定)。
我建议尝试Math.PI - angle
。
tan(angle) = 对边/邻边
arctan(对边/邻边) = angle
对边 = a.y - b.y
邻边 = b.x - a.x
Math.Atan((a.Y - b.Y) / (b.X - a.X));
public static class FunAngleCalc
{
public static double angle(MathPoint p1, MathPoint center, MathPoint p2)
{
MathPoint transformedP1 = new MathPoint(p1.x - center.x, p1.y - center.y);
MathPoint transformedP2 = new MathPoint(p2.x - center.x, p2.y - center.y);
double angleToP1 = Math.Atan2(transformedP1.y, transformedP1.x);
double angleToP2 = Math.Atan2(transformedP2.y, transformedP2.x);
return toDegrees(normaliseToInteriorAngle(angleToP2 - angleToP1));
}
private static double normaliseToInteriorAngle(double angle)
{
if (angle < 0)
{
angle += (2 * Math.PI);
}
if (angle > Math.PI)
{
angle = 2 * Math.PI - angle;
}
return angle;
}
private static double toDegrees(double radians)
{
return 360 * radians / (2 * Math.PI);
}
}
由于您使用了 Vector2 类,我猜您可以使用
a-b
来获取从 a 到 b 的向量。
因此,您需要的角度是:π - angle(a-b)。
Math.Atan2(b.Y - a.Y,b.X - a.X);
可以翻译为“求点 b 相对于点 a 的方向角度,使用反正切函数 Math.Atan2() 计算,其中参数为 b.Y - a.Y 和 b.X - a.X”。 - Shmiddty0
到斜边的角度。所以,我认为你想要:Math.PI - angle
。 - Shmiddty