如何从两个坐标计算角度?

时间:2011-12-01 06:11:01

标签: c# geometry

我正在开发一个基于3D的对象的项目,并通过我的程序进行操作。我目前有一个文本框,允许我在一个度数和一个按钮,它将计算所需的值,使我的主要对象改变其标题。这是该函数的代码:

    private void btnSetHeading_Click(object sender, EventArgs e)
    {
        if (this.textBoxHeading.Text.Length == 0)
            return;

        float heading = (float)0;
        try
        {
            heading = float.Parse(this.textBoxHeading.Text);
        }
        catch (FormatException ex)
        {
            MessageBox.Show(ex.Message);
            return;
        }

        if (heading < (float)0 || heading > (float)360)
        {
            MessageBox.Show("Invalid heading parameter. Acceptable range: 0 - 360");
            return;
        }

        float tempCosine = (float)Math.Cos(((heading * Math.PI) / (float)360.0));
        float tempSine = -((float)Math.Sin(((heading * Math.PI) / (float)360.0)));
        try
        {
            ProgramInterop.CreateInstance.SetHeading(tempCosine, tempSine);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Caught: " + ex.Message);

        }
    }

如果我提供90作为面对的标题,结果是tempCosine = 0.7071068和tempSine = -0.7071068,然后使我的主要对象面向90度或正东方。

程序要求标题以两个单独的值(tempCosine和tempSine)给出,我不熟悉几何,足以理解为什么我会乘以360而不是180,但这就是它需要工作的方式。 / p>

现在我的项目的下一部分涉及使我的主对象面对另一个对象,给出它们的(x,y)坐标。例如,如果我的主要对象位于(9112.94,22088.74)并且我想要面对的新对象位于(9127.04,22088.88),那么它将需要几乎正好90度的方向使其面向新对象。

如何从这两个坐标计算tempCosine和tempSine?

2 个答案:

答案 0 :(得分:3)

关于180,这是真的。我习惯了这样的扩展类来处理弧度和度数。

public static class Extension
{

    public static double ToRadians(this double degree)
    {
        return degree * Math.PI / 180;
    }

    public static double ToDegrees(this double val)
    {
        return val * 180 / Math.PI;
    }
}

关于正弦和余弦(我不确定我是否理解正确的事情)但是如果我使用下面的代码

float x1 = 9112.94f;
float y1 = 22088.74f;

float x2 = 9127.04f;
float y2 = 22088.88f;

float r = (float) Math.Pow((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1), 0.5);
float cosine = (x2 - x1) /r;
float sine = (y2 - y1) /r;

我将获得角度0.5712978(不等于90)。

很抱歉,如果我误解了这个问题。

答案 1 :(得分:2)

我能够使用Dani建议使用Atan2(y,x)来解决问题。谢谢Dani。

float x1 = 9112.94f;
float y1 = 22088.74f;

float x2 = 9127.04f;
float y2 = 22088.88f;

float angleRadians;

float diffX = x2 - x1;
float diffY = y2 - y1;

float atan2Result = (float)Math.Atan2(diffX, diffY);
angleRadians = atan2Result / 2;
if (angleRadians < 0.0f)
    angleRadians += (float)Math.PI;

float tempCosine = (float)Math.Cos(angleRadians);
float tempSine = -((float)Math.Sin(angleRadians));