Select Frame 1 of the Actions layer on the main Timeline. With the Actions panel open, add the following script:
var tvPower:Boolean = false;
function togglePower() {
var newChannel:Number;
if (tvPower) {
newChannel = 0;
tvPower = false;
} else {
newChannel = 1;
tvPower = true;
}
tv_mc.screen_mc.gotoAndStop(newChannel+1);
remote_mc.light_mc.play();
}
The first line of this script creates a variable named
tvPower, which is used to track the current state of the TV. A value of
true means the television is on;
false means the television is off. The television will appear off initially, so
tvPower is set to
false.
The next 11 lines represent a function definition for
togglePower(). When called, this function will toggle the television power on and off. No parameters are passed into this function. Because this script exists on Frame 1, our
togglePower() function is defined, and a variable called
tvPower is set to
false as soon as the frame is loaded (that is, when the movie begins to play).
Note
Because functions must be defined before they can be called, it is common practice to define all functions on an early frame in your movie so that they can be called at any time after that.
The first part of the function uses an
if statement to analyze the current value of
tvPower. If
tvPower is
true (TV is on) when the function is called, the actions in the function change it to
false (off) and set the value of the
newChannel variable to 0; otherwise (
else),
tvPower is set to
true and
newChannel to 1. Using the
if statement in this manner causes the value of
tvPower to be set to its opposite each time the function is called, thus toggling the value of
newChannel. By the time this statement is finished,
newChannel has a value of
0 or
1.
Note
We use if statementsconditional logicin a few places throughout this lesson. They are not formally covered until Lesson 4, "Arrays and Loops." For now, it is enough to know that they are used to determine whether a certain condition is met. If that condition is met, extra code will be executed.
The function then sends the
screen_mc movie clip instance (which is inside the
tv_mc movie clip instance) to a frame based on the current value of
newChannel + 1. You must add 1 to the value of
newChannel to prevent the Timeline from being sent to Frame 0 (
newChannel sometimes contains a value of 0, and there's no such thing as Frame 0 in a Flash movie Timeline). In the end, this part of the function will send the
screen_mc movie clip instance to Frame 1 (showing a blank TV screen) or Frame 2 (showing Channel 1).
The function finishes by telling the light on the remote control to play, which causes it to blink, providing a visual indication that a button has been pressed.
There is now a function on Frame 1 of the main, or root, Timeline. Although this function contains several actions, none of them is executed until the function is called.