home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam

## 2.6. Some Applied Examples

Example 2-6 chooses a random destination for the playhead of a movie.

#### Example 2-6. Send the Playhead to a Random Frame on the Current Timeline

```var randomFrame;            // Stores the randomly picked frame number
var numFrames;              // Stores the total number of frames on the timeline
numFrames = _totalframes;   // Assign _totalframes property to numFrames

// Pick a random frame
randomFrame = Math.floor(Math.random( ) * numFrames + 1);

gotoAndStop(randomFrame);   // Send playhead to chosen random frame```

Example 2-7 determines the distance between two clips. A working version of this example is available from the online Code Depot.

#### Example 2-7. Calculate the Distance Between Two Movie Clips

```var c;         // A convenient reference to the circle clip object
var s;         // A convenient reference to the square clip object
var deltaX;    // The horizontal distance between c and s
var deltaY;    // The vertical distance between c and s
var dist;      // The total distance between c and s

c = _root.circle;       // Get reference to the circle clip
s = _root.square;       // Get reference to the square clip
deltaX = c._x - s._x;   // Compute the horizontal distance between the clips
deltaY = c._ y - s._ y;   // Compute the vertical distance between the clips

// The distance is the root of (deltaX squared plus deltaY squared).
dist = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY));

// Tidy references are much more readable than the alternative:
dist = Math.sqrt(((_root.circle._x - _root.square._x) * (_root.circle._x -
_root.square._x)) + ((_root.circle._ y - _root.square._ y) * (_root.circle._ y -
_root.square._ y)));```

Example 2-8 converts between Fahrenheit and Celsius. A working version is available in the online Code Depot.

#### Example 2-8. A Fahrenheit/Celsius Temperature Converter

```var fahrenheit;           // Temperature in Fahrenheit
var celsius;              // Temperature in Celsius
var convertDirection;     // The system we are converting to.
// Legal values are "fahrenheit" and "celsius"
fahrenheit = 451;                // Set a Fahrenheit temperature
celsius = 20;                    // Set a Celsius temperature
convertDirection = "celsius";    // Convert to Celsius in this case

if (convertDirection == "fahrenheit") {
result = (celsius * 1.8) + 32;   // Calculate the Celsius value.
// Display the result
trace (celsius + " degrees Celsius is " + result + " degrees Fahrenheit.");
} else if (convertDirection == "celsius") {
result = (fahrenheit - 32) / 1.8;   // Calculate the Fahrenheit value.
// Display the result
trace (fahrenheit + " degrees Fahrenheit is " + result + " degrees Celsius.");
} else {
trace ("Invalid conversion direction.");
}```