获得点和原点之间的角度

时间:2013-07-08 15:13:50

标签: c# xna directx angle

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

3点= 90度

6点= 180度

9点= 270度

12点= 0度


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

  

是的,我意识到这看起来简短而且没有建设性,但我做到了   问题尽可能简单易懂。所有其他的   问题已经结束-.-

由于

4 个答案:

答案 0 :(得分:10)

两点A和B之间的矢量是B-A =(B.x-A.x,B.y-A.y)。可以使用dot productatan2计算两个向量之间的角度。

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);

另见Finding Signed Angle Between Vectors

答案 1 :(得分:1)

假设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);
}

答案 2 :(得分:0)

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 
}

答案 3 :(得分:0)

实际上由于原点是(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,因为它试图除以零。

相关问题