Some Applied Examples
We’ve had an awful lot of variable theory. How about showing some of these concepts in use? The following examples provide three variable-centric code samples. Refer to the comments for an explanation of the code.
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 thecircle
clip object var s; // A convenient reference to thesquare
clip object var deltaX; // The horizontal distance betweenc
ands
var deltaY; // The vertical distance betweenc
ands
var dist; // The total distance betweenc
ands
c = _root.circle; // Get reference to thecircle
clip s = _root.square; // Get reference to thesquare
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 plusdeltaY ...
Get ActionScript: The Definitive Guide 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.