In: Categories » Computers and technology » Flash » ActionScript: Performing Actions Conditionally
|
You want to perform an action only when a condition is true. Use an if statement or a switch statement. You often need your ActionScript code to make decisions, such as whether to execute a particular action or group of actions. To execute an action under certain circumstances, use one of ActionScript's conditional statements: if, switch, or the ternary conditional operator (? :). The conditional statements allow you to make logical decisions, and you'll learn from experience which is more appropriate for a given situation. The if statement is most appropriate when you want to tell your Flash movie to do something only when a certain condition is met (i.e., when the condition is true). When you have several possible conditions to test, you can use the switch statement instead. And you can use Flash's ternary conditional operator to perform conditional checking and assignment on a single line. First, we'll look at the if statement. Of the conditional statements in ActionScript, the if statement is the most important to understand. In its most basic form, an if statement includes the keyword if followed by the test expression whose truthfulness you want to evaluate to determine which action or actions to execute. The test expression must be in parentheses, and the statement(s) to be executed should be within curly braces (the latter is mandatory if there is more than one statement in the statement block). Here, we check whether animalName contains the word "turtle". This might be used to check whether the user answered a quiz question correctly (here, animalName is a variable assumed to contain the user's answer). Note that the double equals sign (==) is used to test whether two items are equal. It should not be confused with the single equals sign (=), which is used to assign a value to an item. if (animalName == "turtle") {
// This trace( ) statement executes only when animalName is equal to "turtle".
trace("Yay! 'Turtle' is the correct answer.");
}
Additionally, you can add an else clause to an if statement to perform alternative actions if the condition is false. Note that the trace( ) command has no effect when the Flash movie is running in a browser, so it is intended for testing purposes only. We use the gotoAndStop( ) command to jump to a different frame (presumably one that displays an appropriate message) depending on whether the user answered the question correctly or incorrectly. if (animalName == "turtle") {
// These statements execute only when animalName is equal to "turtle".
trace("Yay! 'Turtle' is the correct answer.");
gotoAndStop("CongratulationsScreen");
}
else {
// These statements execute only when animalName is not equal to "turtle".
trace("Sorry, you got the question wrong.");
gotoAndStop("TryAgainScreen");
}
The gotoAndStop( ) command jumps to a frame with the specified label or frame number and is used in this example to illustrate typical real-world usage. The example assumes you've created a Flash movie with frames labeled "CongratulationsScreen" and "TryAgainScreen." To label a frame, highlight one of the layers in the timeline and add a label using the Frame field in the Property inspector. You can add an else if clause to an if statement. If the if condition is true, the else if clause is skipped. If the if condition is false, the ActionScript interpreter checks to see if the else if condition is true. if (animalName == "turtle") {
// This trace( ) statement executes only when animalName is equal to "turtle".
trace("Yay! 'Turtle' is the correct answer.");
}
else if (animalName == "dove") {
// This trace( ) statement executes only when animalName is not "turtle" but is
// "dove".
trace("Sorry, a dove is a bird, not a reptile.");
}
What if the preceding example was written as two separate if statements (one to check if animalName is "turtle" and another to check if it is "dove")? The example would work as intended, but it would be less efficient. Using the else if statement guarantees that if animalName is "turtle", we don't bother checking if it is also equal to "dove". If your two conditions are mutually exclusive, use an else if clause to check the second condition. If your two conditions are not mutually exclusive, and you want to perform both statement blocks when both conditions are met, use two separate if statements. When you use an if statement with both else if and else clauses, the else clause must be the last clause in the statement. The final else clause is convenient as a catchall; it's where you can put statements that take the appropriate action if none of the other conditions are met. if (animalName == "turtle") {
// This trace( ) statement executes only when animalName is equal to "turtle".
trace("Yay! 'Turtle' is the correct answer.");
}
else if (animalName == "dove") {
// This statement executes only when animalName is not "turtle" but is "dove".
trace("Sorry, a dove is a bird, not a reptile.");
}
else {
// This statement executes only when animalName is neither "turtle" nor "dove".
trace("Sorry, try again.");
}
You can also include more than one else if clause in an if statement. However, in that case, you should most likely use a switch statement instead; generally, switch statements are more legible and succinct than the comparable if statement. Where performance is critical, some ActionScripters prefer to use if statements, which allow somewhat greater control for optimization purposes. A switch statement is composed of three parts: The switch keyword Every switch statement must begin with the switch keyword. Test expression This is an expression, enclosed in parentheses, whose value you want to test in order to determine which actions to execute. The switch statement body The statement body, enclosed in curly braces, is composed of cases. Each case is composed of the following parts: The case or default keyword Each case must begin with a case keyword. The exception is the default case (analogous to an else clause in an if statement), which uses the default keyword. Case expression This is an expression whose value is compared to the switch statement's test expression. If the two values are equal, the code in the case body is executed. The default case (the case that uses the default keyword) does not need a case expression. Case body This is one or more statements, usually ending in a break statement, to be performed if the case is true. The switch keyword is always followed by the test expression in parentheses. Then, the switch statement body is enclosed in curly braces. There can be one or more case statements within the switch statement body. Each case (other than the default case) starts with the case keyword followed by the case expression and a colon. The default case (if one is included) starts with the default keyword followed by a colon. Therefore, the general form of a switch statement is: switch (testExpression) {
case caseExpression:
// case body
case caseExpression:
// case body
default:
// case body
}
Here is an example. Note that once a case tests true, all the remaining actions in all subsequent cases within the switch statement body also execute. This example is most likely not what the programmer intended: var animalName = "dove"; /* In the following switch statement, the first trace( ) statement does not execute
because animalName is not equal to "turtle". But both the second and third trace( )
statements execute, because once the "dove" case tests true, all subsequent code
is executed.
*/
switch (animalName) {
case "turtle":
trace("Yay! 'Turtle' is the correct answer.");
case "dove":
trace("Sorry, a dove is a bird, not a reptile.");
default:
trace("Sorry, try again.");
}
Normally, you should use break statements at the end of each case body to exit the switch statement after executing the actions under the matching case. The break statement terminates the current switch statement, preventing statements in subsequent case bodies from being executed erroneously. You don't need to add a break statement to the end of the last case or default clause, since it is the end of the switch statement anyway: var animalName = "dove"; // Now, only the second trace( ) statement executes.
switch (animalName) {
case "turtle":
trace("Yay! 'Turtle' is the correct answer.");
break;
case "dove":
trace("Sorry, a dove is a bird, not a reptile.");
break;
default:
trace("Sorry, try again.");
}
The switch statement is especially useful when you want to perform the same action for one of several matching possibilities. Simply list multiple case expressions one after the other. For example: switch (animalName) {
case "turtle":
case "alligator":
case "iguana":
trace("Yay! You named a reptile.");
break;
case "dove":
case "pigeon":
case "cardinal":
trace("Sorry, you specified a bird, not a reptile.");
break;
default:
trace("Sorry, try again.");
}
ActionScript also supports the ternary conditional operator (? :), which allows you to perform a conditional test and an assignment statement on a single line. A "ternary" operator requires three operands, as opposed to the one or two operands required by unary and binary operators. The first operand of the conditional operator is a conditional expression that evaluates to true or false. The second operand is the value to assign to the variable if the condition is true, and the third operand is the value to assign if the condition is false. varName = (conditional expression) ? valueIfTrue : valueIfFalse; One common use of the ternary operator is in assigning default values to variables in functions if a parameter value was omitted when calling the function. For example: function myFunction (param) {
var val = (param != undefined) ? param : "default value";
}
The preceding example can be written using an if statement: function myFunction (param) {
var val;
if (param != undefined) {
val = param;
} else {
val = "default value";
}
}
Either way is correct; however, the ternary operator requires fewer lines of code and executes faster. Here is an example in which salutation defaults to "Hello" if no greeting was specified; otherwise, salutation is set to greeting's value. function welcome (greeting) { Here are some examples of the results: welcome( ); // Displays: Hello Sailor!
welcome("Ahoy"); // Displays: Ahoy Sailor!
|
legal disclaimer
1) Our website is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringements, please read the Terms of service and contact us to investigate the problem.
2) The E-articles directory team is not responsible for inaccuracies, falsehoods, or any other types of misinformation this tutorial may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. Please read the Terms of service
Useful tools and features
related articles
Use the beginFill( ) and endFill( ) methods to initiate and close a shape drawn at runtime. To draw a filled shape, call beginFill( ) prior to any other drawing methods, including the custom methods you have defined such as drawCircle( ) and drawPolygon( ). Invoke endFill( ) after calling other drawing methods to create the shape. You cannot apply a fill to an existing shape drawn at authoring time or runtime. You must invoke beginFill( ) before drawing the shape to be filled. This example creates a solid blue ...
2. Drawing a rectangle using ActionScript
Create a custom MovieClip.drawSimpleRectangle( ) method using the Drawing API and invoke it on a movie clip. To draw a simple rectangle, specify the stroke's attributes using the lineStyle( ) method and then draw four lines using the lineTo( ) method: // Create rectangle_mc with a depth of 1 on the main timeline. _root.createEmptyMovieClip("rectangle_mc", 1); // Specify a one-pixel, solid, black line. rectangle_mc.lineStyle(1, 0x000000, 100); // Draw four lines to form the perimeter ...
3. How to draw a rectangle with rounded corners
You want to draw a rectangle with rounded corners, an offset, or rotation.Create a custom MovieClip.drawRectangle( ) method using the Drawing API and invoke it on a movie clip. The drawSimpleRectangle( ) method is, as the name suggests, quite simple. Let's create a more complex version that also: Draws a rectangle with a specified angle of rotation Let's you specify the rectangle center's coordinates Can draw a rectangle with rounded corners The drawRectangle( ) method accepts...
4. Reusing and Organizing Code in Flash Movies
You want to reuse code that you've created for one project in another Flash movie. Or you want to write your ActionScript code in an external text editor. Place your ActionScript code in external .as files and use the #include directive to add them to your Flash movies: // Adds all the code within MyActionScriptFile.as to your Flash movie. #include "MyActionScriptFile.as" Use the #include directive to incorporate code from external text files into your Flash movie during compilation from a .fla file ...
Create a custom MovieClip.drawCircle( ) method using the Drawing API and invoke it on a movie clip. You can create a circle in ActionScript with eight curves. Fewer curves results in a distorted circle and too many curves hinders performance. Let's create a custom method of the MovieClip class for drawing circles. This method, drawCircle( ), allows for three parameters: radius The radius of the circle x The x coordinate of the circle's center point. If undefined, the circle is centered at x =...
6. ActionScript: Repeating a Task at Timed Intervals
You want to perform an action or actions at a specific timed interval. Use the setInterval( ) function. The setInterval( ) function allows you to specify an interval (in milliseconds) at which your Flash movie will invoke a function. Use setInterval( ) to perform a particular action over time but not necessarily at the frequency of the frame rate of the movie. // Define a function. function myIntervalFunction ( ) { // Output the difference between the current timer value and its value from the ...
7. Mouse Location Flash Script
Not only can you get the location of a movie clip on the screen, you can even get the location of the mouse, also known as the cursor. What is the difference between the mouse and the cursor? The mouse is the physical device attached to your computer. You may even have a track pad or tablet instead. The cursor is the graphic that moves around the screen as you move your mouse. So, technically, cursor is the term I should be using here. However, ActionScript uses the term mouse in its keywords. I will therefore use mouse and cursor i...
8. Enhancing Standalone Projector
You want to create an enhanced Standalone Projector with features such as borderless playback, custom titles, no Flash menus, and so on. Use a third-party tool such as SWF Studio or SWFKit to create the Projector from your completed Flash movie. SWF Studio is a third-party utility that helps you overcome some of the limitations of regular standalone Flash Projectors. However, SWF Studio produces Windows projectors only. Also note that the resultant projector files are rather hefty (minimum file size is around 1.5 MB). The...
9. How to build an animated button using Flash
Time: 15 Minutes. Difficulty Level: Intermediate Requirements: Flash 8 Assumed Knowledge: Basic actionscripting, using the actions window, using variables, creating symbols. Purpose: I always wanted to animate a button from ActionScript and keep my timeline clear but it was kind of hard, until I stumbled upon this Tweening Engine from Extend. This tutorial makes use of the Tweening Engine to animate a butt...
10. Using Mathematical Operators in ActionScript
You want to modify something over time, such as the rotation or position of a movie clip. Use the compound assignment operators to change a variable or property in increments. Or, if incrementing or decrementing by one, use the prefix or postfix increment or decrement operators. Often, you'll want the new value of a variable or property to depend on the previous value. For example, you might want to move a movie clip to a new position that is 10 pixels to the right of its current position. In an assignment statement—a...










