向我们展示返回错误结果的代码代码,向我们展示问题所在,并允许我们为您提供更具体的建议.
由于您需要相对于中心的角度,因此必须从点中减去中心坐标.
Math.Atan2
屈服弧度.将它们转换为度数degrees = radians * 180 / pi
.
您的零角度在x轴上不常见,但在y轴上.添加90度进行校正.
使用矢量类型可以简化操作.在这里,我将使用System.Numerics.Vector2
结构.
正如帕特里克麦克唐纳指出的那样,在某些情况下,Atan2可能会产生负面结果.通过向结果添加450度(360 +我们的90度校正)并将此模数取为360度,您总是得到0到360之间的值.
public static float GetAngle(Vector2 point, Vector2 center)
{
Vector2 relPoint = point - center;
return (ToDegrees(MathF.Atan2(relPoint.Y, relPoint.X)) + 450f) % 360f;
}
public static float ToDegrees(float radians) => radians * 180f / MathF.PI;
Run Code Online (Sandbox Code Playgroud)
考试
var a = new Vector2(7, 3);
var b = new Vector2(20, 7);
var c = new Vector2(7, 10);
var d = new Vector2(3, 7);
var e = new Vector2(6.9f, 3); // Test for more than 270 deg.
var f = new Vector2(7.1f, 3); // Test for small angle.
var center = new Vector2(7, 7);
PrintAngle(a); // ==> 0
PrintAngle(b); // ==> 90
PrintAngle(c); // ==> 180
PrintAngle(d); // ==> 270
PrintAngle(e); // ==> 358.5679
PrintAngle(f); // ==> 1.432098
void PrintAngle(Vector2 point)
{
Console.WriteLine(GetAngle(point, center));
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
504 次 |
最近记录: |