I need to know angle of rotation in polar coordinates using X and Y from cartesian coordinates.
How to do it in JS without a lot of IF statements? I know that I can do it using ,
but I think that it will be bad for performance, because it is in animation cycle.
Javascript comes with a built in function that does what is represented in the image: Math.atan2()
Math.atan2()
takes y, x
as arguments and returns the angle in radians.
For example:
x = 3
y = 4
Math.atan2(y, x) //Notice that y is first!
//returns 0.92729521... radians, which is 53.1301... degrees
I wrote this function to convert from Cartesian Coordinates to Polar Coordinates, returning the distance and the angle (in radians):
function cartesian2Polar(x, y){
distance = Math.sqrt(x*x + y*y)
radians = Math.atan2(y,x) //This takes y first
polarCoor = { distance:distance, radians:radians }
return polarCoor
}
You can use it like this to get the angle in radians:
cartesian2Polar(5,5).radians
Lastly, if you need degrees, you can convert radians to degrees like this
degrees = radians * (180/Math.PI)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With