5.12. Converting Angle Measurements

Problem

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

Solution

Create custom degToRad( ) and radToDeg( ) methods.

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 Math.as 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 π and dividing by 180.
Math.degToRad = function(deg){
  return (Math.PI * deg) / 180;
};

// Convert radians to degrees by multiplying by 180 and dividing by π.
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 π/2)
trace(Math.radToDeg(Math.PI));    // Displays: 180

These two methods are invaluable when ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.