简体   繁体   English

C#在2个给定点之间找到角度

[英]C# finding angle between 2 given points

In the program that I'm working on, I have an object (the player) in the shape of a triangle, and that triangle is supposed to rotate always facing the mouse. 在我正在处理的程序中,我有一个三角形形状的对象(播放器),并且该三角形应该始终面向鼠标旋转。 given this two points I have tried different equations I've found online but non of them seem to work or at least preform well enough. 考虑到这两点,我尝试了在网上找到的不同方程式,但它们似乎都不起作用或至少表现得很好。

delta_x = cursor.X - pos.X;
delta_y = cursor.Y - pos.Y;
cursorAngle = (float)Math.Atan2(delta_y, delta_x) * (float)(180 / Math.PI);

this is the most efficient formula I found but it is still not working well enough, since it only faces the mouse at specific angles or distances. 这是我发现的最有效的公式,但是它仍然不能很好地工作,因为它只能以特定的角度或距离面对鼠标。 Cursor.X and .Y are the coordinates of the mouse and pos.X and .Y are the coordinates of the player. Cursor.X和.Y是鼠标的坐标,而pos.X和.Y是播放器的坐标。

I created this WinForm example that calculates the angle and distance of the mouse from the center of the form every time you move the mouse on the form. 我创建了这个WinForm示例,每次在窗体上移动鼠标时,该示例都会计算鼠标到窗体中心的角度和距离。 The result I display in a label. 结果显示在标签中。

在此处输入图片说明

The red dot in the center of the form is just a reference panel and has no relevance in the code. 表单中心的红点只是一个参考面板,与代码无关。

    private void f_main_MouseMove(object sender, MouseEventArgs e)
    {
        Point center = new Point(378, 171);
        Point mouse = this.PointToClient(Cursor.Position);

        lb_mouseposition.Text = $"Mouse Angle: {CalculeAngle(center, mouse)} / Distance: {CalculeDistance(center, mouse)}";
    }


    private double CalculeAngle(Point start, Point arrival)
    {
        var deltaX = Math.Pow((arrival.X - start.X), 2);
        var deltaY = Math.Pow((arrival.Y - start.Y), 2);

        var radian = Math.Atan2((arrival.Y - start.Y), (arrival.X - start.X));
        var angle = (radian * (180 / Math.PI) + 360) % 360;

        return angle;
    }

    private double CalculeDistance(Point start, Point arrival)
    {
        var deltaX = Math.Pow((arrival.X - start.X), 2);
        var deltaY = Math.Pow((arrival.Y - start.Y), 2);

        var distance = Math.Sqrt(deltaY + deltaX);

        return distance;
    }

The angle is here shown in degrees varying from 0 to 359. I hope this helps in calculating the angle between your two points. 角度以度为单位显示,范围从0到359。我希望这有助于计算两个点之间的角度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM