Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Design > Adobe Creative Suite

This chapter is from the book

Writing your first script

Now that we have all the information we need as well as a rough storyboard for our project, let's begin assembling it.

1) Open Windows Notepad or Apple Simple Text to create a new text file, and type the following:

&electricBill=60 

Figure 3

In the first part of this exercise we'll create the source for the data to be loaded into our movie when it plays. For our project, this data source contains a value representing the amount of the electric bill. When Flash loads this text file, it interprets this line of text and creates within the movie a piece of data (called a variable) named electricBill and assigns it a value of 60. The value of this variable will be used several ways in our project.

NOTE

Loading data into Flash from external sources is discussed in detail in Lesson 11, Moving Data in and out of Flash. Variables are discussed in detail in Lesson 6, Working with Dynamic Data.

2) Name the text file Electric_Bill.txt and save it in the folder that contains the files for this lesson, then open electricbill1.fla in the Lesson 1/Assets folder.

Because the focus of this book is ActionScript, not how to use Flash, you'll find that with the exception of setting up scripts, our project elements are largely in place.

Our project's main timeline contains five layers, each of which are 10 frames long. The layers will be named in such a way that their content is evident. Currently, the Actions layer is empty.

3) Open the Property inspector, then select the text field in the upper left corner of the scene, just under the text that reads "Amount you owe is:". In the Property inspector, give this text field an instance name of owed.

Figure 4

Since this text field will be used to display the amount of the electric bill, we've named it owed.

NOTE

In Flash 5, giving text fields variable names was the preferred way of identifying them for use in ActionScript. In Flash MX, however, text fields are now instances of the new Text Field object. As such, they are now identified using instance names. Although you can still assign variable names to text fields, some of the new functionality afforded Text Field objects will not be available if you do so. Thus, it's better to use instance names to identify text fields.

4) With the Property inspector still open, select the text field under the text that reads, "Amount you would like to pay is:". In the Property inspector, give this text field an instance name of paid.

Looking at the Property inspector, you'll notice that this is an Input Text field. It will be used to accept input from the user, specifically the amount he or she wants to pay toward the electric bill. We've entered zero (0) in this text field, so that's the amount that will appear initially when our movie plays.

5) With the Property inspector still open, select the text field at the bottom of the scene, under the Switch button. In the Property inspector, give this text field an instance name of message.

This text field will be used to display a custom message to our user, depending on how much he or she chooses to pay.

6) With the Property inspector open, select the lightbulb movie clip instance and name it light.

Since our script will affect this movie clip instance, we must give the movie clip instance a name so that we can tell the script what to do with it. This movie-clip instance has three frame labels (Off, On, and Hot) on its timeline that represent how it will look under various conditions. Initially it will appear as Off.

Figure 5

In our script (which we'll set up in a moment), we want the movie clip to remain at this label if the user pays less than what he or she owes—that is, the light won't come on because the user hasn't paid enough. If the user pays the exact amount, we want to send the clip's timeline to the frame label On—that is, we want the light to come on. If the user pays too much, we want the clip's timeline to go to the frame labeled Hot so that the light appears to be getting more juice than it needs.

Now that all of our scene elements are named, we're ready to begin scripting; we'll begin by instructing our movie to load the data from our external text file.

7) With the Actions panel open (and set to Expert Mode), select Frame 1 of the Actions layer, and enter the following script:

loadVariablesNum ("Electric_Bill.txt", 0); 

NOTE

We suggest you leave the Actions panel in Expert Mode because it represents the easiest way to enter most of the scripts discussed in this book.

This line of script does one thing: It loads the variables from the Electric_Bill.txt file (which we created earlier) into Level 0, which is the movie file we're working on now. The Electric_Bill.txt file contains a single variable named electricBill with a value of 60. Thus, after this line of script has executed, our movie will contain an electricBill variable with a value of 60. This process simply transfers the variables from our text file into our movie.

loadVariablesNum() is an action. We make it work a specific way by placing unique parameter values inside the parentheses. This particular action has two parameter settings, separated by a comma. The first setting is used to indicate the source containing the external data; the second is used to indicate the timeline into which to load the data. You'll find that many ActionScript elements can accept multiple parameter settings in a similar fashion.

We've placed this script on Frame 1 of our movie so that it will be executed as soon as the movie begins playing—important since our movie needs the electricBill value in order for the script that we'll be adding to the Light Switch button to work.

8) Add a keyframe to Frame 10 of the Actions layer. Then, with the Actions panel open, enter the following script on that keyframe:

owed.text = electricBill; 
stop (); 

Figure 6

As set up in the last step, Frame 1 contains an action that will load the variables in the Electric_Bill.txt file. The movie's timeline continues to play as the text file loads; then, when it reaches Frame 10, the above actions are executed.

The first action will set the value displayed in the owed text field instance to equal the value of electricBill. You'll remember that owed is the instance name we assigned to the text field in the upper-left corner of our project, and that electricBill is the variable loaded in from our text file with a value of 60. Thus, this line of script will cause the number 60 to appear in the owed text field.

As mentioned earlier, text fields are now considered objects in Flash MX. As such, they also have numerous properties. One of the new properties of a text field instance is its text property. This property is used to designate the text displayed in an instance. The above script demonstrates how this property is used to set the text displayed in the text field instance named owed. Notice how a dot (.) separates the object name from the name of its property. In ActionScript, this is how you specify that you want to work with something specific concerning the object—in this case, one of its properties.

The first line also demonstrates the use of an operator between two elements, an object property and a variable (and its value). Here, the equals sign (=) is used to tell the script to assign the value of the electricBill variable to the text property of the owed text field instance.

The last action in the script simply stops the timeline from playing. Because this action does not require any unique parameter values, the parentheses are left empty.

TIP

You'll notice that there's a span of several frames between the frame containing the action to load the variables from the text file and the Frame 10 action that actually uses the electricBill variable that's been loaded. This allows time for the text file to actually load. If we tried to use the electricBill variable before the text file had finished loading, we would encounter problems. In fact, our movie might act as if the text files had never loaded. A frame cushion, as we've created here, is one way to prevent problems. We'll discuss other ways in later lessons.

Now it's time to set up the script for our Light Switch button.

9) With the Actions panel open, select the Light Switch button and enter the following script:

on (press) { 
 amountPaid = Number(paid.text); 
 amountOwed = Number(owed.text); 
} 

The first thing to notice about this script is that it executes when the button it's attached to is pressed. Following this event is an opening curly brace ({), a couple lines of script, then a closing curly brace (}). These curly braces are used to say, "Do these two things as the result of the button being pressed."

The above script accomplishes two things: First, a variable named amountPaid is created and its value is set to equal that displayed in the paid text field instance—though with a twist. Normally, anything entered in a text field is considered text. Thus, even if a value of 100 appears in the text field as numerals, it's considered text (consisting of the characters 1, 0, and 0, or "100" with quotes) rather than the number 100 (without quotes).

NOTE

The fact that Flash considers everything entered in a text field to be text is a default behavior. Even though the user may not add quotes when typing into a text field, Flash invisibly adds them so that the movie knows that the value is a text value.

You can think of the Number() function as a specialized tool that allows you to convert a text value to a numerical value in such a way that ActionScript recognizes it as a number instead. You need to place the text that you want to convert between the parentheses of the function. For example:

myNumber = Number("945"); 

This will convert the text "945" to the number 945 (no quotes) and assign that number value to the variable named myNumber. In the above script, we used the Number() function and placed a reference to the text value to be converted between the parentheses of the function. Thus, if the user types "54" (text initially) into the paid field, the Number function causes amountPaid to be given a value of 54 (no quotes, thus the number 54) as well.

NOTE

The Number() function does have its limitations: You can only use it to convert something that is potentially a number in the first place. For example, Number("dog") results in NaN (not a number) because a numeric conversion is not possible.

The next line in the script does essentially the same thing, only the value of amountOwed is set to equal the converted-to-a-number value displayed in the owed text field instance. You'll remember that this text field instance displays the amount of the electric bill, or "60". Thus, after the conversion takes place, amountOwed is given a value of 60.

The reason for converting the values in the text fields in this way is that most of the rest of the script will be using them to make mathematical evaluations/calculations—which means it needs to see them as numbers, not text, in order for them to work.

In summary, when the button is pressed, the text values displayed in the paid and owed text fields are converted to numbers. These number values are assigned to the variables named amountPaid and amountOwed, respectively. These variable values will be used in the remainder of the script.

10) With the Actions panel still open, add the following lines of script to the script created in the previous step. Add them within the curly braces ({}), just below where it says amountOwed = Number(owed.text);: if (amountPaid < amountOwed) {

difference = amountOwed - amountPaid;
  light.gotoAndStop ("Off");
  message.text = "You underpaid your bill by " + difference + " dollars.";
} else if (amountPaid > amountOwed) {
  difference = amountOwed - amountPaid;
  light.gotoAndStop ("Hot");
  message.text = "You overpaid your bill by " + difference + " dollars.";
} else {
  light.gotoAndStop ("On");
  message.text = "You have paid your bill in full.";
}

Since we added these lines of script within the curly braces of the on(press) event, they are also executed when the button is pressed.

This part of the script is essentially broken into three parts, identified by the following lines:

if (amountPaid < amountOwed) 
else if (amountPaid > amountOwed)
else 

Figure 7

These three lines represent a series of conditions the script will analyze when executed. The condition to be analyzed is specified between the parentheses. Underneath each of these lines in the script (between additional curly braces) are several lines of indented script, which represent the actions that will be executed if that particular condition proves true. Here's how it works:

When our Light Switch button is pressed, we want our script to determine whether the amount the user enters to pay is more, less, or equal to the amount owed. That's what the three conditions our script analyzes are all about. Let's review the first condition, which looks like this:

if (amountPaid < amountOwed) {
 difference = amountOwed - amountPaid;
 light.gotoAndStop ("Off");
 message.text = "You underpaid your bill by " + difference + " dollars.";
}

The first line is a less-than operator (<) used to compare the value of one variable to another. It basically states, "If the amount the user enters to pay (amountPaid) is less than the amount he or she owes (amountOwed), take the actions below." These actions are only executed if this condition is true. And if they are executed, it's as a group, which is why they're placed within their own set of curly braces. The first action creates a variable named difference and assigns it a value of amountOwed minus amountPaid. If the user has entered 40 as the amount to pay, difference would have a value of 20 (amountOwed – amountPaid, or 60 – 40). It's important to note that any equation to the right of the equals sign is calculated prior to assigning the calculated value to the item to the left. The next line tells the light movie clip instance to go to and stop at the frame labeled Off. Since this action is only executed if the user underpays his or her bill, it's appropriate that the light stays off. The last line will generate a custom message to be displayed in the message text field.

We call this a custom message because of the way the message is constructed within the script. Note the use of the difference variable in this line: The value of difference is inserted in the middle of this message between the two sections of quoted text and the plus signs. If difference has a value of 20 (as described above), this message would read:

"You underpaid your bill by 20 dollars."

Remember that anything within quotes is considered plain text. Because difference is not enclosed in quotes, ActionScript knows that it references a variable's name and thus will insert that variable's value there. The plus sign (+) is used to concatenate (join) everything to create a single message. The equals sign is used to assign the final, concatenated value to the text property of the message text field.

If the amount the user enters to pay is the same as what's owed, or more, this part of the script is ignored and the next part of the script is analyzed. It reads as follows:

else if (amountPaid > amountOwed) {
 difference = amountOwed - amountPaid;
 light.gotoAndStop ("Hot");
 message.text = "You overpaid your bill by " + difference + " dollars.";
}

The first line here states, "If the amount the user enters to pay is more than the amount he or she owes, take the actions below." The actions executed here are just variations on the ones discussed above—with a couple of minor differences: The first difference is that the light movie clip instance is sent to the frame labeled Hot, which displays a light bulb getting too much energy to signify that the user has overpaid. The second difference comes in the wording of the custom message. Instead of saying underpaid, here it says overpaid. The actions in this section are only executed if the user pays more than what's owed. If that's not the case, these actions are ignored and the last part of the script is analyzed. It reads as follows:

else {
 light.gotoAndStop ("On");
 message.text = "You have paid your bill in full.";
}

You'll notice that here the script doesn't begin by asking if amountPaid is more or less than amountOwed (as did the first two sections). This is because the script wouldn't be carrying out this analysis if the user had entered the exact amount owed—that is, this part of the script will only execute if neither of the first sections do.

In the end, when the button is pressed, only one of these three actions will execute. As a result, the light movie clip instance will appear a certain way and a custom message will appear in the message text field.

When the Light Switch button is released, we want to reset the elements in our scene so that they appear as they did when the movie first played. Let's add that functionality.

11) With the Actions panel open and the Light Switch button still selected, enter the following script at the end of the current script:

on (release) {
 light.gotoAndStop ("Off");
 message.text = "";
}

Figure 8

This script is triggered when the button is released. It will send the light movie clip instance to the frame labeled Off and empty the message text field, returning these scene elements to their original state.

12) Save this file as electricBill2.fla.

We'll use this file in the next exercise in this lesson.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020