C# 数学计算来检索两点之间的角度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12891516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:51:40  来源:igfitidea点击:

Math Calculation to retrieve angle between two points?

c#mathdistanceangle

提问by Luke Joshua Park

Possible Duplicate:
How to calculate the angle between two points relative to the horizontal axis?

可能的重复:
如何计算两点之间相对于水平轴的角度?

I've been looking for this for ages and it's just really annoying me so I've decided to just ask...

我一直在寻找这个,这真的让我很烦,所以我决定问问......

Provided I have two points (namely x1, y1, and x2, y2), I would like to calculate the angle between these two points, presuming that when y1 == y2 and x1 > x2 the angle is 180 degrees...

假设我有两个点(即 x1、y1 和 x2、y2),我想计算这两个点之间的角度,假设当 y1 == y2 和 x1 > x2 时,角度是 180 度...

I have the below code that I have been working with (using knowledge from high school) and I just can't seem to produce the desired result.

我有我一直在使用的以下代码(使用高中的知识),但我似乎无法产生所需的结果。

float xDiff = x1 - x2;
float yDiff = y1 - y2;
return (float)Math.Atan2(yDiff, xDiff) * (float)(180 / Math.PI);

Thanks in advance, I'm getting so frustrated...

在此先感谢,我感到非常沮丧......

采纳答案by phant0m

From what I've gathered, you want the following to hold:

根据我收集的信息,您希望保留以下内容:

  • Horizontal line: P1 -------- P2=> 0°
  • Horizontal line: P2 -------- P1=> 180°
  • 水平线:P1 -------- P2=> 0°
  • 水平线:P2 -------- P1=> 180°

Rotating the horizontal line clockwise

顺时针旋转水平线

You said, you want the angle to increase in clockwise direction.

你说,你想顺时针方向增加角度。

Rotating this line P1 -------- P2such that P1is above P2, the angle must thus be 90°.

旋转这条线P1 -------- P2使其P1在 上方P2,因此角度必须为 90°。

If, however, we rotated in the opposite direction, P1would be below P2and the angle is -90° or 270°.

但是,如果我们以相反的方向旋转,P1则会在下方P2且角度为 -90° 或 270°。

Working with atan2

atan2

Basis: Considering P1to be the origin and measuring the angle of P2relative to the origin, then P1 -------- P2will correctly yield 0.

基础:考虑P1为原点并测量P2相对于原点的角度,P1 -------- P2则将正确产生0

float xDiff = x2 - x1;
float yDiff = y2 - y1;
return Math.Atan2(yDiff, xDiff) * 180.0 / Math.PI;

However, atan2let's the angle increase in CCW direction. Rotating in CCW direction around the origin, ygoes through the following values:

但是,atan2让我们在 CCW 方向上增加角度。绕原点逆时针方向旋转,y经过以下值:

  • y = 0
  • y > 0
  • y = 0
  • y < 0
  • y = 0
  • y = 0
  • y > 0
  • y = 0
  • y < 0
  • y = 0

This means, that we can simply invert the sign of yto flip the direction. But because C#'s coordinates increase from top to bottom, the sign is already reversed when computing yDiff.

这意味着,我们可以简单地反转 的符号y来反转方向。但是因为C#的坐标是从上往下增加的,所以计算的时候符号已经颠倒了yDiff