Recipe 5.12 Converting Angle Measurements

5.12.1 Problem

You want to work with angle values in ActionScript, but you must convert to the proper units.

5.12.2 Solution

Create custom degToRad( ) and radToDeg( ) methods.

5.12.3 Discussion

The _rotation property of a movie clip object is measured in degrees. Every other angle measurement in ActionScript, however, uses radians, not degrees. This can be a problem in two ways. First of all, if you want to set the _rotation property based on the output of one of ActionScript's trigonometric methods, you must convert the value from radians to degrees. Second, humans generally prefer to work in degrees, which we must convert to radians before feeding to any of the trigonometric methods. Fortunately, the conversion between radians and degrees is simple. You should add the following degToRad( ) and radToDeg( ) methods to your file for converting from degrees to radians and vice versa. Note that they are attached directly to the top-level Math object, making them available throughout your movie.

// Convert degrees to radians by multiplying by p and dividing by 180.
Math.degToRad = function(deg){
  return (Math.PI * deg) / 180;

// Convert radians to degrees by multiplying by 180 and dividing by p.
Math.radToDeg = function(rad){
  return (rad * 180) / Math.PI;

This following code demonstrates how the methods work:

trace(Math.degToRad(90));         // Displays: 1.5707963267949 (which is p/2)
trace(Math.radToDeg(Math.PI));    // Displays: 180

These two methods are invaluable when you want to use the trigonometric methods:

// Use degToRad(  ) to convert degrees to radians before passing the value to 
// Math.cos(  ) (which expects radians). 

// Get the angle (in radians) for a cosine of .75 using the inverse cosine.
angle = Math.acos(.75);
// Set MovieClip._rotation to the degree equivalent of the angle in radians.
myMovieClip._rotation = Math.radToDeg(angle);

5.12.4 See Also

Recipe 5.15

    Part I: Local Recipes
    Part II: Remote Recipes