Search code examples
c#mathatan2

how to calculate the angle in degrees using Atan2()


i need your help with this code i have here:

    Console.WriteLine();
    Console.WriteLine("Enter first X value: ");
    float point1X = float.Parse(Console.ReadLine());
    Console.WriteLine("Enter first Y value: ");
    float point1Y = float.Parse(Console.ReadLine());
    Console.WriteLine("Enter second X value: ");
    float point2X = float.Parse(Console.ReadLine());
    Console.WriteLine("Enter second Y value: ");
    float point2Y = float.Parse(Console.ReadLine());
    Console.WriteLine();

        double deltaX = point2X - point1X;
        double deltaY = point2Y - point1Y;
        double distance = Math.Sqrt(Math.Pow(deltaX, 2) + Math.Pow(deltaY,2)) ;

double angleX = Math.Atan2(point1X,point1Y);

        Console.WriteLine("DeltaX value is: " + deltaX);
        Console.WriteLine("DeltaY value is: " + deltaY);
        Console.WriteLine("The distance is: " + distance);
        Console.WriteLine("The angle is: " + angle + "°");

    }
}

Basically I need help with that line that is separated from the rest. I want to calculate the angle between 2 points and print it on degrees. I know it's a very simple code, but I have to deliver it for a qualified job.

Note 1: I have to use Atan2 () obligatorialy.

Note 2: I have to calculate the angle between the vector of the 2 points.

Note 3: Here's some crappy drawing of what i need

https://i.sstatic.net/31tvB.png

Note 4: The user puts 2 coordinates, one for the first point and one for the second point. What i need to calculate is the angle between the vectors of the 2 points.


Solution

  • The main job is done in this method:

    static double Angle(double x1, double y1, double x2, double y2)
    {
        double angle1 = Math.Atan2(y1, x1);
        double angle2 = Math.Atan2(y2, x2);
        return Math.Abs(angle1 - angle2) * 180 / Math.PI;
    }
    

    Combining with your code, it becomes:

    class Program
    {
        static double Angle(double x1, double y1, double x2, double y2)
        {
            double angle1 = Math.Atan2(y1, x1);
            double angle2 = Math.Atan2(y2, x2);
            double angle = Math.Abs(angle1 - angle2) * 180 / Math.PI;
            return angle;
        }
    
        static void Main(string[] args)
        {
            Console.WriteLine();
            Console.Write("Enter first X value: ");
            float point1X = float.Parse(Console.ReadLine());
            Console.Write("Enter first Y value: ");
            float point1Y = float.Parse(Console.ReadLine());
            Console.Write("Enter second X value: ");
            float point2X = float.Parse(Console.ReadLine());
            Console.Write("Enter second Y value: ");
            float point2Y = float.Parse(Console.ReadLine());
    
            Console.WriteLine($"\nAngle between these points is {Angle(point1X, point1Y, point2X, point2Y)} degrees.");
        }
    }