Last active
January 11, 2016 17:13
-
-
Save motss/ebc393166084bfbc9081 to your computer and use it in GitHub Desktop.
Mapping clock angle using Math.atan2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 1 - Start off everything from the origin (0, 0) just like how to draw something on a graph in Mathematics | |
* where the Cartesian Plane has a +ve and -ve x- and y- axes and the circle is drawn on it by having a | |
* centroid at the origin (0, 0); | |
* 2 - Do the same thing for finding an angle from a coordinate as you know a circle has 360 degree, however | |
* the method to find a particular angle from the coordiante you have chosen is kind of not doing what | |
* you would have expected. Say, the method you use to find the angle is by using Math.atan2, it actually | |
* returns a computed angle from the X axis and the range of the returned value falls between -pi and +pi. | |
*/ | |
/** | |
* 3 - Conversion is needed for the returned value to make them fit into the degree of a circle which has 360 | |
* instead of any angle of -ve value. To do so, see the code below: | |
*/ | |
// Regular method to find an angle from a coord. on a Cartesian plane. | |
function _evalAngleFromCircleAtOrigin(point_from_y_axis, point_from_x_axis) { | |
return Math.atan2(point_from_y_axis, point_from_from_x_axis); | |
} | |
// Method to find an angle from a given coord. on a computer graphics. | |
function _evalAngleFromCircleAtOriginWithConversion(point_from_y_axis, point_from_x_axis) { | |
/** | |
* - invert x and y due to compute graphics has only +ve and -ve x- and y-axes so that the angle will | |
* be computed from the y axis instead of x axis. | |
* - turning y into -ve value is to invert the values of y so that it starts from the top of inverted y-axis. | |
*/ | |
return Math.atan2(point_from_x_axis, -(point_from_y-axis)); | |
} | |
// Further convert the return angle to any value from 0 to 2pi. | |
function _convertAngle(angle) { | |
/** | |
* - the above method only transform how normally the atan2 method finds an angle from a circle on the | |
* Cartesian plane and by doing that everything will look exactly how a typical clock works, having the number | |
* 12 from the top of the clock and moving indefinitely in clockwise direction. | |
* - however, the second half of the circle (or clock) are still in -ve values and we need to do some magic to | |
* make those numbers to become +ve so that the degree will go from 0 to 360 in the whole circle in each | |
* successive clockwise direction. | |
*/ | |
return angle <= 0: 360 + angle: angle; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment