Domanda

Given a point (x,y), how do I calculate the angle from the x-axis?

        |    . <- (x,y)
        |   /
        |  /
        | /
        |/
--------+---------
        |
        |

Currently I have

Math.atan(y/x) * 180 / Math.PI;

However, this does not represent all the coordinates properly. Here are the results for this in each of the quadrants (counterclockwise).

Quadrant 1: 0 -> -90
Quadrant 2: 90 -> 0
Quadrant 3: 0 -> -90
Quadrant 4: 90 -> 0

How can I write a statement that will give me the angle from the x-axis of any point such that the results for the quadrants look like this.

Quadrant 1: 0 -> 90
Quadrant 2: 90 -> 180
Quadrant 3: 180 -> 270
Quadrant 4: 270 -> 360

Basically how do I make this work in all four quadrants?

È stato utile?

Soluzione

Use Math.atan2() because it returns a value from 0->180 in the first two quadrants and -180->0 in the last 2.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top