Basic grammar rules for ActionScript

Source: Internet
Author: User
Tags date define constant expression include inheritance variables visibility
Syntax This tutorial details the basic grammar rules to follow when writing scripts using ActionScript, and is a must-read tutorial for as beginners ...

When scripting with ActionScript, you can create simple actions using the normal-mode action Panel, menu and list selection options. To write powerful scripts in ActionScript, you have to delve into and learn about the ActionScript scripting language for Flash MX.

Like other scripting languages, ActionScript also has its own syntax rules for variables, functions, objects, operators, reserved keywords, and other language elements. ActionScript allows users to create their own objects and functions. ActionScript's syntax and style are very similar to JavaScript, but not exactly the same. ActionScript has its own syntax and punctuation rules that specify the meaning of characters and keywords, and the order in which they are written. For example, you end a sentence in English with a period, and in ActionScript you end a statement with a semicolon.

  The following are some of the basic syntax rules for ActionScript, and for more specific rules, see the ActionScript dictionary.

 1. Point syntax

In ActionScript, Dot (.) Used to indicate the properties and methods associated with an object or movie clip. It also uses an identity to target the path to a movie clip or variable. The point syntax expression begins with the object or movie clip name, followed by a point, and finally the property, method, or variable to be specified. For example, an expression ballmc.x refers to the _x property of a movie clip instance BALLMC, and _x movie clip properties indicate the x-axis position of the movie clip in the editing area.

For example, submit is a variable that is set in the movie clip form, and the form is a movie clip that is nested in the movie clip ShoppingCart. The function of an expression shoppingcart.form.submit=true is to set the value of the submit variable of the instance form to true.

Methods that express an object or movie clip follow the same pattern. For example, the play method for a BALLMC instance is used to move a BALLMC's timeline playhead, as in the following statement:

Ballmc.play ();

The point syntax uses two special aliases: _root and _parent. The alias _root refers to the main time axis. You can use the _root alias to create an absolute path. For example, the following statement calls the Buildgameboard function of the movie clip functions in the main timeline:

_root.functions.buildgameboard ();

Flash MX allows you to use the alias _parent to refer to a movie clip that is nested in the current movie clip. You can also create a relative target path with _parent. For example, if a movie clip dog is nested in a movie clip animal, the following statement on the instance dog tells the animal movie clip to stop playing:

_parent.stop ();

 2. Slash syntax

A previous version of Flash uses the slash syntax to indicate the target path of a movie clip or variable. The Flash MX player still supports this syntax, but is deprecated. In the slash syntax, the slash is used in place of a point to indicate the path of a movie clip or variable. To indicate a variable, you can precede the variable with a colon, as shown in the following statement:

Mymovieclip/childmovieclip:my Variable

We now replace the above slash syntax with the dot syntax to represent the target path above:

MyMovieClip.childMovieClip.myVariable

The slash syntax is most commonly used in telltarget actions, but this action is no longer recommended in Flash MX.

"description" instead of using the Telltarget action, use the with action to be compatible with the point syntax.

  3. Curly Braces

ActionScript statements are divided in braces ({}), as shown in the following script:

On (release) {   mydate = new Date ();   Currentmonth = Mydate.getmonth ();}

 4. Semicolon

The ActionScript statement ends with a semicolon (;), but if you omit the semicolon at the end of the statement, Flash can still successfully compile your script. For example, the following statement ends with a semicolon:

Colum = Passeddate.getday (); row = 0;

The same statement can also be written without a semicolon:

Colum = Passddate.getday () row = 0

  5. Parentheses

When you define a function, you put the argument in parentheses:

function MyFunction (name, age, reader) {  ...}

When you call a function, you also put the arguments you want to pass in parentheses:

MyFunction ("Steve", 10,true);

Parentheses can be used to change the operation precedence of ActionScript, or to make the ActionScript statements you write easier to read.

You can also use parentheses to compute the expression on the left side of the point-syntax point. For example, in the following statement, parentheses cause the expression new color (this) to be evaluated and a new color object is created:

Onclipevent (enterframe) {  (new Color (This)). Setrgb (OXFFFFFF);}

In the example above, if you do not use parentheses, you need to add a statement in your code to compute it:

  Onclipevent (enterframe) {    MyColor = new Color (this);    Mycolor.setrgb (0XFFFFFF); }

 6. Uppercase and lowercase letters

In ActionScript, only keywords are case-sensitive. For the rest of ActionScript, you can use uppercase or lowercase letters. For example, the following statement is equivalent:

Cat.hilite = true;
Cat.hilite = true;

However, it is a good habit to adhere to consistent case-by-letter conventions. This makes it easier to distinguish between the names of functions and variables when reading ActionScript code. If you do not use the correct capitalization when writing a keyword, your script will have an error. For example, the following two statements:

SetProperty (Ball,_xscale,scale);
SetProperty (Ball,_xscale,scale);

The previous sentence is correct, the last sentence in the property of P should be uppercase and not uppercase, so it is wrong. When you enable the color syntax feature in the Actions panel, the keywords that are written in the correct case are displayed in blue, so it is easy to find the spelling errors of the keywords.

7. Note

When you need to remember the role of an action, you can use the comment (note) statement in the Actions panel to add a comment to a frame or button action. If you work in a collaborative environment or provide an example to others, adding a comment can help others to understand the script you are writing.

When you select the comment action in the action panel, the character "//" is inserted into the script. Even more complex scripts are easy to understand if you add comments when you create a script, such as:

  On (release) {    //Create a new Date object    = MyDate = Update ();    Currentmonth=mydate.getmonth ();    Converts the month represented by a number to the month    MonthName = Calcmoth (Currentmonth), which is expressed in words;    Year = Mydate.getfullyear ();    currentdate = Mydate.getdat ();  }

In the Script window, the annotation content is displayed in pink. They are not limited in length and do not affect the size of the exported file.

  8. Key words

ActionScript retains some of the words that are specifically used in the language. Therefore, you cannot use these reserved words as the names of variables, functions, or labels. The following table lists all the keywords in ActionScript:

Break continue Delete Else
for function if in
New return to this typeof
var void while with

Note These keywords are lowercase and cannot be written in uppercase form.

  9. Constant

Constants have properties whose values never change. Constants are listed in uppercase letters in the Action Toolbox. For example, constant backspace, ENTER, QUOTE, return, space, and tab are properties of the key object, which refers to the key on the keyboard. To test whether the user is pressing the ENTER key, use the following statement:

  if (keycode () = =key. ENTER) {    alert = "Are you ready?" "    Controlmc.gotoandstop (5);  }

Terminology in ActionScript

ActionScript uses specific terminology based on specific grammatical rules. The following alphabetical introduction of important ActionScript terminology.

Actions: A statement that directs Flash movies to perform certain actions while playing. For example, a gotoandstop action can convert a playhead to a specified frame or frame marker.

Action (action) can also be called statement (statement).

Arguments: is a placeholder that allows a value to be passed to a function. For example, the function welcome in the following statement uses two parameters FirstName and hobby to receive the value:

function Welcome (firstname,hobby) {welcometext = "Heelo," + FirstName + "I" and "enjoy" + hobby;}

Classed (Class): is a variety of data types. Users can create "classes" and define new types of objects. To define the class of an object, the user creates a constructor function.

Constants (constant): is the element that will not change. Constants are useful for comparison of values.

Constructors (constructor): A function that defines the properties and methods of a "class". The following code generates a new circle class by creating a circle constructor function.

function Circle (x, y, radius) {this.x =  x; this.y = y; this.radius = radius;}

Data types: A set of values and operations that can be performed. The data types of ActionScript include: strings, numeric values, logical values, objects, and movie clips.

Events: Actions that occur during a movie's playback. For example, when a movie is cropped, when the playhead reaches a frame, when the user clicks a button or movie clip, and when the user presses a button on the keyboard, a different action occurs.

Expressions (expression): is a statement that can produce a value. For example, 2+2 is an expression.

Functions (function): is a code snippet that can reuse and pass parameters, and can return a value. For example, the GetProperty function can use the instance name and the property name of the movie clip to return the property value. The GetVersion function can return the version of the Flash Player that currently plays the movie.

Handlers (handle): a special action that can manage such things as MouseDown and load events. For example, Onmouseevent and Onclipevent are the handles of ActionScript.

Identifiers (identifier): is used to indicate the name of a variable, property, object, function, or method. The first letter of an identifier must be a character, an underscore (_), or a dollar sign ($). Subsequent characters can be characters, numbers, underscores, or dollar signs. For example, FirstName is a variable name.

Instances (instance): is an object belonging to some class (class). An instance of each class contains all the properties and methods of the class. For example, all movie clip instances contain properties of the MovieClip class (Transparency properties, visibility properties), and methods (such as gotoAndPlay, Geturl, and so on).

Instance names (instance name): is a unique name. Can be specified as a target in the script.

Keywords (keyword): is a reserved word with special meaning. For example, VAR is a keyword that can be used to define local variables.

Methods (method): is a function assigned to an object. After a function is assigned to an object, the function can be called the method of the object.

Objects (object): is a collection of attributes. Each object has its own name and value. Object allows users to access certain types of information. For example, the predefined object date for ActionScript provides information about the system clock.

Operands: is a value that is manipulated by an operator in an expression.

Operators (operator): The new value can be computed from one or more values. For example, a new value can be obtained by adding two values.

Parameters (parameter): Also known as arguments (parameter).

Properties: Is the Attributer (property) that defines the object. For example, all movie clip objects have _visible (visibility) properties, which enable you to determine whether a movie clip is displayed.

Target paths (destination path): Is the vertical hierarchical address of movie clip names, variables, and objects in a Flash movie. The name of the main timeline is _root. You can name an instance of a movie clip in the movie clip property Inspector.

The user can point the action to the movie clip through the target path, or you can use the target path to get or set the value of the variable. For example, the following example statement is the path to the variable volume inside the movie clip Stereocontrol:

-root.stereocontrol.volume

Variables (variable): is an identifier that stores a value of any data type. Variables can be created, modified, and updated. The values stored in the variable can be retrieved by the script. In the following example, the variable identifier is on the left side of the equal sign, and the value of the variable is assigned to the right:

x = 5;name = "Lolo"; customer.address = "7th Street"; c = new Color (mcinstancename);

  Writing ActionScript scripts

Writing flash action scripts does not require users to have a complete understanding of ActionScript, and the user's needs are the real goal. With design creativity, the user chooses the appropriate action, attribute, function, or method to do so. The best way to learn about ActionScript is to create a script. Users can create simple scripts with the help of the action panel. Once you are familiar with adding basic actions such as play and stop in a movie, users can begin to learn more about ActionScript. To use the power of ActionScript, it's important to understand how ActionScript languages work: The basics of ActionScript language, elements, and rules for organizing information and creating interactive movies.

 1. Script Planning and debugging

The number and variety of scripts can be huge when you write scripts for the entire movie. For example, you might want to consider the following questions: Decide which actions to use, how to create a more efficient script structure, and where to place the script? All of these issues need to be carefully planned and tested. Especially when the film becomes more and more complex, these problems become more prominent.

Before you start writing scripts, users need to be clear about what they want to achieve. For example, the goal might be to create an entire site using Flash.

? Ask the site visitor's name and reuse that information throughout the site.

? The site has a navigation toolbar that you can drag to help users jump to any branch of the site.

? When a button is clicked, the new content appears in the middle of the stage in a fading way.

? Create a user-specific scene that contains a form that has been filled in with the user's name.

Once you have made it clear what the animation is for, users can start creating objects and scripting to control those objects.

Having your scripts work the way you want them to, usually takes time than writing a script. Users need to constantly test whether their scripts are working properly. The best way to achieve this is to save a version of a file by starting with a simple script, testing it frequently, writing and testing a part of the working script. This method of working helps users debug script errors more effectively and has a solid foundation for writing more complex scripts.

  2. Object-oriented scripting

In Object-oriented programming methods, users organize information by classifying information into groups. Users can create multiple instances of a type of information for use in scripts. Users can use ActionScript's predefined Class (class), or they can create their own classes. ActionScript's built-in classes are located in the objects (object) folder of the action on the Board.

When you create a class (class), the user defines all attributes (attributes) and methods (behavior) for each object created by the class. This is the same as the method of defining objects in the real world. For example, "person" has attributes such as sex, height, and hair color, and the behavior of "person" includes speaking, walking, throwing, etc., in this example, "person" is a class, and each individual is an instance of that class, that is, object.

Objects in ActionScript can contain data, or they can be movie clips on the stage. All movie clips are instances of a predefined MovieClip class. Each movie clip instance has all the attributes of the MovieClip class (such as _height, height, _rotation, rotation, _totalframes, total number of frames, and so on) and all methods (for example, gotoAndPlay, go to and play; Loadmovie, Load into a movie; StartDrag, start dragging, etc.).

To define Class (class), the user needs to create a special function called a constructor. The predefined classes of flash already have constructor functions defined. For example, if you need information about a cyclist in a movie, you can create a constructor function named biker. The function includes the time and distance properties, as well as the speed method, which tells the user the speed at which the rider travels.

function Biker (T, d) {this.time = t; this.distance = D;} function Speed () {return this.time/this.distance;} Biker.prototype.rate = Speed;

After writing the constructor function, the user can create a copy of the Biker class, namely: an instance. The following code can create an instance of the Biker class object Emma and Hamish:

Emma = new Biker (5); hamish = new Biker (40,5);

Instances can also communicate with each other. For example, for objects in the biker class, a user can create a shove (push) method that allows one cyclist to push another cyclist. In this way, when the Hamish instance is too close, the Emma instance can invoke the Shove method and push the Hamish away. To pass information to a method, you can use parameters. For example, the shove (push) method can carry the WHO (pushed) and Howfar (push how far) parameters, such as the following example.

Emma.shove (Hamish, 10);

In Object-oriented programming methods, classes can receive properties and methods from each other in a specified order, which is called inheritance. Users can use inheritance to extend or redefine the properties and methods of a class. Classes that inherit properties and methods from other classes are called "subclasses," and classes that pass properties and methods to other classes are called "superclass", and a class can be both "subclass" and "superclass".

  3. The process of the script

Flash executes the ActionScript statement from the first line of statements, always sequentially to the final statement or to the statement that ActionScript specifies to jump to.

The actions that send execution orders to other places rather than the next statement include: If statements, Do...while loops, and return actions.

An If statement is called a conditional judgment statement or a "logical branch" because it controls the scripting process based on the evaluation of certain conditions. For example, the following code checks whether the value in the variable mynumber is less than or equal to 10, and if the check result returns True (for example, the value of MyNumber is 5), then variable alert sets the text string value and displays its value in the Output text field.

if (MyNumber <=10) {  alert = "The number is less than or equal to 10";}

Users can also add the Else statement to create more complex conditional judgment statements. In the following example, if the condition judgement returns True (for example, the value of the variable MyNumber is 3), the statement between the first set of braces executes, and the alert variable displays the value of the second row. If the conditional judgement returns false (for example, the value of the variable MyNumber is 30), the first set of code areas will be skipped and the statement between the curly braces following the Else statement will be executed.

if (MyNumber <=10) {  alert = "The number is less than or equal to 10";} else {  alert = "The number is greate than 10";}

A loop statement repeats an action several times until a certain condition is satisfied. In the following example, the movie clip will be copied 5 times.

i = 0;do {  duplicatemovieclip ("Mymovieclip", "Newmovieclip" +i,i);  NewName = eval ("Newmovieclip" +i);  SetProperty (Newname,_x,getproperty ("Mymovieclip", _x) + (i*5));  I=i+1}while (i<=5);

  4. The script runs

When writing scripts, users can use the actions panel to attach scripts to frames in the timeline, or to buttons or movie clips on the stage. The script attached to the frame executes when the playhead arrives at the frame, while the script attached to the button or movie clip executes when an event occurs. The so-called "event" can be a movie when the mouse moves, a button is pressed, can also be a movie clip is loaded and so on. Using ActionScript, you can discover when an operation occurred and then execute the specified script based on that event.

Actions attached to a button or movie clip are surrounded by a special action called Handler (handlers), onclipevent and on actions are called handlers because they manipulate or manage operations. Users can specify one or more actions for each handler. The movie clip or button action is performed when the event specified by the handler occurs. If you want to perform different actions when different events occur, you can attach multiple handlers to an object.

The Onclipevent action handles the event for the movie clip, while the on action handles the button's events. Users can also use the on action with movie clips to create a movie clip that accepts mouse events.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.