C# finding angle between 2 given points

6k views Asked by At

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.

1

There are 1 answers

2
Alberto Santos On BEST ANSWER

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. The result I display in a label.

enter image description here

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.