ItsCrumbz
ItsCrumbz

Reputation: 9

Why am I Getting Incorrect Results When I use Math.Atan2

The program takes two points to find the distance between the two points and find the angle to get from point one to point 2. The distance portion works fine but when I use Math.Atan2 to find the angle I get an inccorect answer.

    //these are the variables the store the points
    static float point1X = 2;
    static float point1Y = 2;
    static float point2X = 4;
    static float point2Y = 4;
    
    //This is the code I use to find the distance
    float deltaX = point1X - point2X;
    float deltaY = point1Y - point2Y;

    float step1 = MathF.Pow(deltaX, 2f) + MathF.Pow(deltaY, 2f);
    float distance = MathF.Sqrt(step1);

    //this is the code used to find the angle
    float radians = (float)Math.Atan2(deltaY, deltaX);
    float angle = radians * (float)(180 / Math.PI);

    Console.WriteLine(distance + " " + angle);
    

I tried the points (2,2) and (4,4). The result I got for the angle was -135. I also tried the points (5,5) and (4,4) which yeilded 45.

Upvotes: 0

Views: 170

Answers (1)

MvG
MvG

Reputation: 60868

When you write deltaX = point1X - point2X then that delta is the signed distance starting at point 2 and ending at point 1. Your intuition is probably the opposite: start at 1 and end at 2. So you should swap that difference around. Same for y.

How many steps are there from 3 to 8? There are 8 - 3 = 5 steps. See, end minus start is what you'd use in everyday situations, too.

Upvotes: 1

Related Questions