## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

No credit card required

# Using Trigonometry

## Problem

You want to do some advanced animation, involving rotation, circular motion, or oscillation.

## Solution

Use the built-in math functions Math.sin(), Math.cos(), and Math.atan2().

## Discussion

Recipes 11.2 and 11.4 touched on the use of the sine and cosine functions, but they can be used for many other useful effects, such as moving objects in circular or oval paths, smoothly back and forth around a position, or rotating to a particular angle. Both Math.sin() and Math.cos() are based on the properties of a right triangle (a triangle that has one 90-degree angle). Without getting into a trigonometry lesson, if you feed either function a series of increasing numbers, they will return values that go smoothly back and forth from -1 to 0, 1, 0, and back to -1, continuously. The following code snippet demonstrates this:

```for(var i:Number = 0; i < 10; i += 0.1) {
trace(Math.sin(i));
}```

This traces a long list of numbers. If you examine those numbers, you’ll see that they start at 0, go up to 0.999, back down to -0.999, back up, and so on. You can now multiply that by another number, say 40, and get a list of values from -40 to 40. If you use this in an enterFrame handler, or timer-based method, and apply the result to an object’s position, you can get it to oscillate back and forth, or up and down, as the following example shows:

`package { import flash.display.Sprite; import flash.events.Event; public class Oscillation extends Sprite { private var _sprite:Sprite; private ...`

## With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

No credit card required