| Math.cos( ) Method | Flash 5; can be used when exporting Flash 4 movies |
| compute the cosine of an angle |
An angle, in radians (not degrees), normally in the range of 0 to
2
, although any angle will suffice, as cosine is a
periodic function.
The cosine of theta (the result is in the range of -1.0 to 1.0).
The cos( ) function returns the trigonometric cosine of an angle. In a right triangle, the cosine of an angle is the result of dividing the length of the side adjacent to the angle by the triangle's hypotenuse.
Note that cos( ) expects angles to be provided in radians, not degrees.
trace (cos(0)); // Displays: 1.0 trace (cos(Math.PI)); // Displays: -1.0
The cos( ) function can be used along with sin( ) to calculate a point on a circle, which we use in the following example to move a movie clip in a circular path. Given the radius of a circle, r, and an angle, xxxthetaxxx, measured counterclockwise from the positive horizontal axis, a point's location is (r*cosxxxthetaxxx, r*sinxxxthetaxxx):
// Global Function: degreesToRadians()
// Converts degrees to radians. There are 2*pi radians per 360 degrees.
_global.degreesToRadians = function (degrees) {
return (degrees/180) * Math.PI;
}
// Method: MovieClip.moveInCircle()
// Desc: Starts moving the clip around a circular path.
// Params: radius Radius of circle path.
// x Horizontal center of circular path.
// y Vertical center of circular path.
// degPerFrame Number of degrees to move per frame rendered.
MovieClip.prototype.moveInCircle = function (radius, x, y, degPerFrame) {
var deg = 0; // Angle of object in degrees, measured
// counterclockwise from the horizon (X-axis).
// Assign a movement function to run once per frame.
this.onEnterFrame = function () {
// Increase the rotation angle by 5 degrees
deg += degPerFrame;
// Place the object. Note that Flash inverts the Y-axis of Cartesian
// coordinates so we decrement y to obtain our new location.
var rotAngRad= degreesToRadians(deg);
this._x = x + Math.cos(rotAngRad) * radius;
this._y = y - Math.sin(rotAngRad) * radius;
}
}
// Usage:
ball_mc.moveInCircle(100, 200, 200, 5);
Math.acos( ), Math.PI, Math.sin( ), Math.tan( )