Question

In C#, how do I calculate the angle between two points given x1, y1, x2, y2 relative to the Y-axis (assuming that x increases from left to right and y increases from top to bottom)?

Was it helpful?

Solution

Try this:

static double GetAngle(double x1, double y1, double x2, double y2)
{
    var w = x2 - x1;
    var h = y2 - y1;

    var atan = Math.Atan(h/w) / Math.PI * 180;
    if (w < 0 || h < 0)
        atan += 180;
    if (w > 0 && h < 0)
        atan -= 180;
    if (atan < 0)
        atan += 360;

    return atan % 360;
}

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top