计算度数失败! [英] Calculating degrees fails!

查看:90
本文介绍了计算度数失败!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我目前正在尝试获得一个点与另一个点之间的度数。

原因是,因为我需要旋转一个我的精灵,我使用一个名为双度的变量。

假设我想计算:



中心点:1,1

度点数:2,2

图像示例: http://i45.tinypic.com/2li910y.png [ ^ ]



我使用以下方法:



Hello everyone,

I am currently attempting to get the degrees between a point and another.
The reason why is, because I need to rotate a sprite of mine, and I use a variable called "double Degrees".
So assuming that I want to calculate:

Central Point: 1,1
Degrees Point: 2,2
Image Example: http://i45.tinypic.com/2li910y.png[^]

I use the following method:

System.Windows.Forms.MessageBox.Show(GetAngleBetween(new Point(1, 1), new Point(2, 2)).ToString());

        public double GetAngleBetween(Point p1, Point p2)
        {
            return Math.Atan(p1.X / p1.Y) - Math.Atan(p2.X / p2.Y);
        }





很明显,从图片看,我应该用角度旋转我的精灵:~45 *

但是,我的void返回0.有人可以向我解释为什么会发生这种情况吗?



Now obviously, looking from the picture, I should rotate my sprite with the angle: ~45*
But, my void returns 0. Can anyone explain to me why this is happening?

推荐答案

首先, p1。 X / p1.Y p2.X / p2.Y 都是1.0,所以<$ c $差异的结果c> Atan 值为0.

从根本上说,你的计算结果不正确,请尝试:

First, p1.X / p1.Y and p2.X / p2.Y are both exactly 1.0, so the result of the difference of the Atan values is 0.
Fundamentally, you''re calculating this incorrectly, try:
public static double GetAngleBetween(Point p1, Point p2)
{
  double deltaX = (double)(p2.X - p1.X);
  if (deltaX < 1e-10)
    return Math.PI / 2.0;
  return Math.Atan(((double)(p2.Y - p1.Y)) / deltaX);
}



此外,请注意,这将从正X方向返回弧度逆时针的角度与原点在点p1 。要从弧度转换为度数乘以 180 /π


Also, note that this returns the angle in radians counterclockwise from the positive X direction with the origin at Point p1. To convert from radians to degrees multiply by 180 / π:

double angle = GetAngleBetween(new Point(1, 1), new Point(2, 2)) * 180.0 / Math.PI;
angle = GetAngleBetween(new Point(0, 0), new Point(1, 2)) * 180.0 / Math.PI;


请查看您之前的问题以及我对不太正确的答案以及我对精度的考虑的评论。



正确使用的功能如下:

http://msdn.microsoft.com/en-us/library/system.math.atan2.aspx [ ^ ]。



此方法自动找到矢量和坐标轴X之间的角度,为每个象限选择合适的sin或cos,以实现最佳精度。



你可以找到这个角度的第一个和第二个矢量分开,然后从另一个角度减去一个角度。根据需要转换为学位。



-SA
Please see you previous question and my comment to the not-quite-correct answers and my considerations about precision.

The right function to use is this:
http://msdn.microsoft.com/en-us/library/system.math.atan2.aspx[^].

This method automatically finds the angle between a vector and coordinate axes X, choosing appropriate sin or cos for each quadrant, to enable optimum precision.

You can find this angle for first and second vector separately, and than subtract one angle from another. Convert to degrees as required.

—SA


这篇关于计算度数失败!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆