We've had an awful lot of variable theory. The following examples provide three variable-centric code samples that show some of these concepts in use. Refer to the comments within the code for an explanation of each line of code.
Example 2-6 sends the playhead of a movie clip to a random destination.
var randomFrame; // Stores the randomly picked frame number var numFrames; // Stores the total number of frames in the clip numFrames = this._totalframes; // Store the current movie clip's // _totalframes property in numFrames // Pick a random frame randomFrame = Math.floor(Math.random( ) * numFrames + 1); this.gotoAndStop(randomFrame); // Send playhead of current movie clip 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.
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 square root of (deltaX squared plus deltaY squared). dist = Math.sqrt((deltaX * deltaX) + (deltaY * deltaY)); // Using variables, the code above creates tidy references that // are much more readable than the alternative, shown below: 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 from Fahrenheit to Celsius. A working version showing bi-directional conversion is available in the online Code Depot.
// Create variables var fahrenheit; // Temperature in Fahrenheit var result; // The value resulting from conversion // Initialize variables fahrenheit = 451; // Set a Fahrenheit temperature // Calculate the Celsius equivalent result = (fahrenheit - 32) / 1.8; // Display the result trace (fahrenheit + " degrees Fahrenheit is " + result + " degrees Celsius.");