获得点和原点之间的角度

这可能以前已经回答过,如果有的话,对不起。 我基本上需要从原点到点获得角度。 那么让我们说Origin是(0,0)而我的目标点是(3,0)

3点= 90度

6点钟= 180度

9点钟= 270度

12点钟= 0度


不知何故,我必须做一些数学魔术,并发现角度是90度(顶部是0)。 原点可能会有所不同,所以我需要一个带有两个参数的方法,Origin和TargetPoint,它们以度为单位返回双倍角度。

是的,我意识到这看起来简短而且没有建设性,但我让这个问题尽可能简单易懂。 所有其他问题都被关闭了 – .-

谢谢

两点A和B之间的矢量是BA =(Bx-Ax,By-Ay)。 两个矢量之间的角度可以用点积或atan2计算。

var vector2 = Target - Origin; var vector1 = new Point(0, 1) // 12 o'clock == 0°, assuming that y goes from bottom to top double angleInRadians = Math.Atan2(vector2.Y, vector2.X) - Math.Atan2(vector1.Y, vector1.X); 

另请参见在矢量之间查找有符号角度

假设x是正数,这样的事情:

 angle = Math.Atan(y / x) * 180 / Math.PI + 90 

编辑为允许负x值:

如果它可能是负面的,只需按案例进行。 像这样的东西:

 if (x < 0) { angle = 270 - (Math.Atan(y / -x) * 180 / Math.PI); } else { angle = 90 + (Math.Atan(y / x) * 180 / Math.PI); } 
 public static double GetAngleDegree(Point origin, Point target) { var n = 270 - (Math.Atan2(origin.Y - target.Y, origin.X - target.X)) * 180 / Math.PI; return n % 360; } static void Main(string[] args) { Console.WriteLine(GetAngleDegree(new Point(0, 0), new Point(0, 3)));//0 Console.WriteLine(GetAngleDegree(new Point(0, 0), new Point(3, 0)));//90 Console.WriteLine(GetAngleDegree(new Point(0, 0), new Point(0, -3)));//180 Console.WriteLine(GetAngleDegree(new Point(0, 0), new Point(-3, 0)));//270 } 

实际上,由于原点是(0,0),所以无法找出点与原点之间的角度。 我们可以计算2点之间的角度,因为它们被视为矢量,因此它们有方向,但原点没有方向。 因此,如果要使用时钟示例查找角度,可以计算点与(1,0)之间的角度,例如该点为0度。

对不起,我不熟悉C#,但你可以看看这个类似的java代码:

 double getAngle2PointsRad(double p1_x, double p1_y, double p2_x, double p2_y) { return Math.acos((((p1_x * p2_x) + (p1_y * p2_y)) / (Math.sqrt(Math.pow(p1_x, 2) + Math.pow(p1_y, 2)) * Math.sqrt(Math.pow(p2_x, 2) + Math.pow(p2_y, 2))))); } double getAngle2PointsDeg(double p1_x, double p1_y, double p2_x, double p2_y) { return Math.acos((((p1_x * p2_x) + (p1_y * p2_y)) / (Math.sqrt(Math.pow(p1_x, 2) + Math.pow(p1_y, 2)) * Math.sqrt(Math.pow(p2_x, 2) + Math.pow(p2_y, 2))))) * 180 / Math.PI; } 

如果你试图用(0,0)计算,你会得到NaN,因为它试图除以零。