ActionScript 3 tutorials: Difference between revisions

The educational technology and digital learning wiki
Jump to navigation Jump to search
m (Text replacement - "<pageby nominor="false" comments="false"/>" to "<!-- <pageby nominor="false" comments="false"/> -->")
 
(68 intermediate revisions by 2 users not shown)
Line 1: Line 1:
{{stub}}
{{incomplete}}
 
<!-- <pageby nominor="false" comments="false"/> -->


== Actionscript 3, the programming language shared by Flash and Flex ==
== Actionscript 3, the programming language shared by Flash and Flex ==


This pages is for actionscript concepts that apply to any ActionScript 3.0 authoring environment and any runtime that supports ActionScript 3.0. For the moment, two authoring environment are covered in this wiki, Adobe [[Flash]] CS3 and [[Adobe Flex]]. The focus is on programming concepts rather than tool-specific topics.
This pages is for actionscript concepts that apply to any [[Flash ActionScript 3 overview|ActionScript 3.0]] authoring environment and any runtime that supports ActionScript 3.0. For the moment, two authoring environment are covered in this wiki, Adobe [[Flash CS3 desktop tutorial|Flash CS3]] and [[Adobe Flex]]. The focus of this page is on programming concepts that are completely tool un-specific (that would work in Flash as well as Flex).


== Disclaimer ==
== Disclaimer ==
Line 28: Line 30:
  var counter:int = 0;
  var counter:int = 0;


* AS3 is an object oriented language. This means that you have the possibility to split your code into specialized classes rather than write a single program of 3,000 lines of code. This contributes to make the code easier to maintain and easier to re-use. You can then design specialized components that will be re-used across different applications. A typical example of such a component would be a calendar object that pops up to let you specify a date.
* AS3 is an object oriented language. This means that you have the possibility to split your code into specialized classes rather than write a single program of 3,000 lines of code. This contributes to make the code easier to maintain and easier to re-use. You can then design specialized components that will be re-used across different applications. A typical example of such a component would be a calendar object that pops up to let you specify a date.
 
The problem then, for a total newbie, is that the use of classes is not optional. *Everything* needs to be organized into classes. You must have at least one class in your program. This can appear quite obscure at first. But because the class definition always uses the same format, that's simply a question of getting used to add these extra lines in your code. Initially you will write short programs that don't justify the use of more than a single class. Don't worry if you don't understand that class concept yet. What matters is that you start going, start writing a bit of code and become able to play around. We will come back on the concept of class soon enough. 
 
// The class definition
public class Game {
    // instance variable of type integer
    var score:int
  // The constructor method
    public function Game () {
          // code that initialize Game instances
    }
   
  // instance method
    public function updateScore ():void {
        // code to execute when updateScore () is invoked
    }
 
With the structure in class comes another concept, the one of package. A package is a conceptual container. It is used to group classes that operate together within a physical region of their own. Its main function is to help organize the code for large applications. Another complex concept to grasp for a total beginner. The recommendation here is the same as for classes. In a first time, simply use the syntax without worrying too much about what it is for. Your are likely to write programs that stand within a single package for a few weeks, so don't worry about not understanding it. We will take the time to explain this in more details, as soon as you are up to it.


== Enough technicalities, let's program! ==
== Enough technicalities, let's program! ==


I don't know for you. I tend to learn best by doing. What gets me through complex learning is the desire to realize things. Of course, it is very important to take the time to understand complex notions thoroughly. However if you are too much worried about understanding every single aspect of the programming language before writing your first line of code, chances are high that you will give up before reaching that point. If you reach that point, the risk is that your head will be so full of unfamiliar concepts that you will completely unsure about what you should be doing next, what option to take.  
Whatever your level, make sure that you read the instructions on [[AS3 Compiling a program|How to compile an AS3 program]]  and that you are successful at compiling the first example given on that page.


Something that I find to work for me is to take a tutorial or book about the language, read it through without trying to understand everything. I do my best to understand the introductory paragraph of each chapter and to browse through the code trying to grasp the gist of how things get done. Then I go back to the beginning and start coding very simple examples. I make sure that I understand them well. I try to produce as many simple variants as I can of these simple examples. I add a new element, then a new one, etc. Once I become familiar enough with the very basic I try to come up with an idea of a little program that I could write that would make use of many of these basic elements. I write the program... I don't give up before I have finished writing it. Even if it takes me 2 or 3 days, I persevere. Once I am okay with writing an original program, I try and come up of ideas of various types of games or activities that I would like to become able to realize. I evaluate which one I can write successfully with what I already know. I evaluate what new concepts I need to master in order to write that program and the likelihood that I can get to learn these concepts in a relatively short amount of time.  I go for the most realistic options.
=== Stage 1, Absolute Novice ===


In this view, what we will do next is
What you need to get started. This assumes absolutely no prior experience with programming whatsoever. Because of this, it can be perceived as a bit dumb and slow-paced for persons who have already done some coding. In this case, simply rapidly browse through, have a look at the demo examples. Because each one explores a simple technique in isolation, they can be used as reference to Beginner and Intermediate coders.
# provide a simple program that is guaranteed to work (copy/paste/run).
# invite you to try and write variants 
# introduce a small number of examples that each introduce a specific technique
# come up with suggestions of mini-games or activities that you could write that use these techniques
# take you through a complete example of such a mini-game.


=== Compiling a first program ===
Go to [[AS3 Tutorials Novice|Novice]]


There are potentially three ways to compile your first actionscript program:
=== Stage 2, Beginner ===
# Compiling with the Flash CS3 Authoring tool
# Compiling with Flex Builder
# Compiling with the binary mxmlc included in the Flex framework.


Here, we will describe how to compile with mxmlc. This assumes that your Flex framework is properly installed. For information on how to install it on the [[Adobe Flex]] page.
This assumes that you have a very basic understanding of the general format and syntax of an AS3 program and know how to compile it. You know how to draw a rectangle on the screen by slightly adapting the code provided, but that's about it. You are a bit lost when it comes to writing your own program from scratch, even the simplest one. Well, you will be given the basic knowledge required to transform simple ideas into simple programs mixing graphics and interactive components. You learn about basic data types and control statements as well as how to use instance functions to organize your code more efficiently.  


Open a text editor, a simple one that will save the text as it appears on the screen, without any formatting. In that new text file, copy the following code:
Go to [[AS3 Tutorials Beginner|Beginner]]


  package  {
=== Stage 3, Intermediate ===
    import flash.display.Sprite;
    public class FilledCircle extends Sprite {
        function FilledCircle():void {
          var circle:Sprite = new Sprite();
          circle.graphics.beginFill(0xFF794B);
          circle.graphics.drawCircle(50, 50, 30);
          circle.graphics.endFill();
          addChild(circle);
        }
    }
  }


Save the file as text and give it the name of "FilledCircle.as".  Take good note of the directory in which you save that file. Preferably, put it in a folder quite high up in the hierarchy. We will assume that the file is stored somewhere defined by "\path\to\file\".
Drawing rectangles and interactive buttons on the screen is all good, but that doesn't get you very far, is it? Here you learn to write more complex programs, like mini-games. These programs are too complex to hold on a single page of code. You are introduced to the gist of some OO concepts. At this level, we have code spread over multiple files, class-based code organisation, inheritance, composition, dispatching events across objects, reading xml data or embedding assets stored locally.


==== On a mac ====
Go to [[AS3 Tutorials Intermediate|Intermediate]]


# Open a terminal window. Terminal is an application like any other. To find it, go to the Applications -> Utilities. You should see Terminal.app among the files.
=== Stage 4, Advanced ===
# Double click on the application to open it.
# At the prompt, type:


  cd \path\to\file\
All you need to know to write the next killer web 2.0 application that will make you rich or to become a professional freelance developer. You get to learn about design patterns and data services. The advanced tutorial will be shared between AS3 and Flex and would assume basic knowledge of Flex.  
  mxmlc FilledCircle.as


==== On a PC ====   
Well, this may remain underdeveloped till I reach that stage myself. Give me a few months. I challenge you to make more rapid progress than I will and actively contribute to the writing of that section!


# From the Windows start menu, open a command prompt by choosing Start > All Programs > Accessories > Command Prompt.
Go to [[AS3 Tutorials Advanced|Advanced]].
# At the command prompt, change to the C:\Flex SDK 2\bin directory then execute the mxmlc executable on your actionscript file.  


  cd C:\Flex SDK 2\bin
== Resources ==
  mxmlc C:\path\to\file\FilledCircle.as


The mxmlc executable will compile the program and generate a .swf file name FilledCircle.swf. To run the file, open it in the Flash Player on your desktop or in a web browser that has Flash Player installed. Note that Flash Player 9 needs to be installed to view swf files generated by the Flex compiler.
* [[AS3 simple examples]]
* [[AS3 Useful links]]
** [[AS3 Links Tutorials|On-line Tutorials]]
** [[AS3 Links Documentation|Reference Manuals and Cheatsheets]]
** [[AS3 Links Documentation|Books]]
** [[AS3 Links Toolkits|Toolkits, Libraries, Reusable Components, Reusable Code]]
* Ideas and Information for programming projects
** [[ProgrammingProjects_Fractals|Fractals]]
** [[ProgrammingProjects_Tessalation|Tesselation]]
** [[ProgrammingProjects_Patterns|Patterns and Symmetry]]
** [[ProgrammingProjects_Puzzles|Puzzles]]
** [[ProgrammingProjects_etivities|Interactive Learning Activities]]
** [[ProgrammingProjects_Games|Games]]
** [[ProgrammingProjects_Makers|Makers]]
** [[ProgrammingProjects_Visualisation|Data Visualisation]]
** [[ProgrammingProjects_MiniApps|MiniApps]]


== Related pages ==
* [[Flash ActionScript 3 overview]]
* [[ActionScript 3 event handling tutorial]]
* [[ActionScript 3 interactive objects tutorial]]


=== How does it work? ===
== Credits ==
 
Okay, let's go through that program step by step to try and understand how this works.
 
----
  package  {
 
No string follow the word package. This means that we don't bother storing our code in independent regions. We have a single package.
----
    import flash.display.Sprite;
 
The import statement is a consequence of the class organisation. Though we won't make use of classes in our very first programs, the thing is that the code that defines how Flash works and how elements are layed out on the screen is defined within a class-based organization. Each class does something very specific. There is one, for instance that contains all the code required for drawing graphics on the screen. This class is the Sprite class. And the Sprite class belongs to the display package which is itself part of the flash package.
 
Greatly simplified, what this means is ... we will need to play with Sprite objects (that is objects that can be drawn into) in this program, so please make all the code associated to Sprite objects available to my program.
 
----
    public class FilledCircle extends Sprite {
 
This is a class definition. This corresponds to saying what follows is the code that defines FilledCircle objects and their behaviors. The extends part means that we want our FilledCircle object to inherit all properties of a Sprite object (more about this later).
----
        function FilledCircle():void {
 
This is an instance constructor. When any part of the program tries to create an object of type FilledCircle, run this code. The best way to conceptualize this is initialization code every time a new object is being created.
----
          var circle:Sprite = new Sprite();
 
What we do here is declare a variable called circle and have it hold the definition of a new Sprite Object. The reason we need to create one is because we want to draw something on the screen. We could draw directly on the screen.. But then we would loose any ability to manipulate the object later on. See it like the contrast between creating graphics on a blackboard and creating graphics with a sophisticated enough image editing software. If you draw a circle on a blackboard, then late on add some text, you might discover that you don't have room enough and you need to move the circle. On a blackboard, you can't. You have to restart from scratch. Erase a part or the totality of the content of the board and start drawing again. When you use an image editing software, if you come to discover that the circle was not drawn at the right location, you can select it and move it somewhere else on the screen without having to redraw it.
 
Well, that's what Sprites are about. They define a small display area able to contain graphics and media content that you can reposition or manipulate later on.
 
We mentioned that AS3 is a strongly typed object. Because of that we have to write ''var circle:Sprite = new Sprite()'' rather than ''var circle = new Sprite()''. We create a variable called circle and we specify to the program that the type of information that this variable will hold is the definition of a Sprite object.
 
----
          circle.graphics.beginFill(0xFF794B);
          circle.graphics.drawCircle(50, 50, 30);
          circle.graphics.endFill();
 
This part draws a circle. It doesn't draw a circle directly on the screen. What it does is to draw a circle within a Sprite object. Because of that, each line starts with circle, the sprite object in which we want the graphics to be added. Then we grab the drawable area ("graphics") and we perform various drawing actions on it. '''beginFill''' specifies that we want to draw filled shapes. What follows is a color parameter. The value of "0xFF794B" is at first sight a bit strange. It defines a color in a format easy to manipulate for a computer. This is exactly the same hexadecimal format than used in HTML in case you are already familiar with it (0xFFFFFF stands for white, 0x000000 stands for black). Let's not spend too much time on this. Color code values can be obtained on this [http://www.webmonkey.com/reference/color_codes/ color code reference page] at webmonkey.com. '''drawCircle''' draws a circle which has for center the point (50,50) (50 pixels from the left, 50 pixels from the top) and for radius 30 (30 pixels). '''endFill''' indicates that we have finished with drawing filled shapes.
 
----
          addChild(circle);
 
Above we mentioned that we didn't draw directly on the screen. What we did was to draw onto a Sprite object. For the circle to appear on the screen, it is necessary to add it to the stage.
----
        }
    }
  }
 
Any parenthesis or bracket that has been opened must be closed.
 
=== Variants ===
 
Try and change the position of the circle and its size. Change the color. Try to draw a [http://images.google.com/images?svnum=10&um=1&hl=en&safe=off&client=safari&rls=en&q=bulleye&btnG=Search+Images bulleye].
 
Why not draw other shapes?
 
For a rectangle, use


sprite.graphics.drawRect(x, y, width, height);
This tutorial was for a good part written at a time where Marielle Lange (widged) was visiting fellow at the [http://www.macs.hw.ac.uk/ School of Mathematical and Computer Sciences, Heriot-Watt University] (Edinburgh, UK). I am most thankful for the office space and collegial environment offered during my 3 months there.


For an ellipse, use


sprite.graphics.drawEllipse(x, y, width, height);
For a rounded rectangle, use:
sprite.graphics.drawRoundRect(x, y, width, height, ellipseWidth, ellipseHeight);
=== Gotchas ===
When you tried to create multiple shapes, did it work? If yes, congratulations! I am really impressed.
If not, what is the error that appeared in your terminal window? I would bet that you got "Warning: Duplicate variable definition". What does it mean? How to fix it?
There is only one variable in the short program we have provided. If you don't remember what it is, run a search on "variable" on this web page. When pressing next to go through all matching strings, you should at some point end up on this sentence "What we do here is declare a variable called circle and have it hold the definition of a new Sprite Object."
This is correct, we declared a variable called circle. An issue with object oriented languages is that variables need to be declared the very first time they are being used. This is the ''var'' part of the line. This means we define something called "circle" that from now on we will use as a variable. You have to declare a variable the very first time you use it. You cannot declare a variable more than once.
If you tried to copy and paste the code multiple times to create multiple shapes, chances are that you did this:
          var circle:Sprite = new Sprite();
          circle.graphics.beginFill(0xFF794B);
          circle.graphics.drawCircle(50, 50, 30);
          circle.graphics.endFill();
          addChild(circle);
          var circle:Sprite = new Sprite();
          circle.graphics.beginFill(0xFF794B);
          circle.graphics.drawCircle(50, 50, 30);
          circle.graphics.endFill();
          addChild(circle);
That doesn't work because twice you get to create a brand new variable that as for name "circle". What you need to do is use a different name each time you create a new variable.
This will work:
          var circle:Sprite = new Sprite();
          circle.graphics.beginFill(0xFF794B);
          circle.graphics.drawCircle(50, 50, 30);
          circle.graphics.endFill();
          addChild(circle);
          var rect:Sprite = new Sprite();
          rect.graphics.beginFill(0x0083D7);
          rect.graphics.drawRect(30, 100, 40, 60);
          rect.graphics.endFill();
          addChild(rect);
=== Challenge ===
Can you draw a house, with roof, chimney, window, door?
If not, what are you missing? What about the roof? How to draw a triangular roof? How to find the information you need to draw a triangle? If you go to google.com and run a search on [http://images.google.com/images?svnum=10&um=1&hl=en&safe=off&client=safari&rls=en&q=%22actionscript+3%22+triangle&btnG=Search+Images "actionscript 3" triangle], do you find any page that help find out how to draw a triangle?
Btw, how to draw a simple line? This could come in handy. After all, a triangle is a shape made of three lines.
If you had no success with Google, try the [http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00000178.html adobe live documentation]. Can you draw a simple line or a triangle now?
== Related pages ==
* [[Flash ActionScript 3 overview]]
* [[ActionScript 3 event handling tutorial]]
* [[ActionScript 3 interactive objects tutorial]]


[[Category: Technologies]]
[[Category: Multimedia]]
[[Category: Multimedia]]
[[Category: Actionscript 3]]
[[Category: Actionscript 3]]
[[Category: Flash]]
[[Category: Flash]]
[[Category: Flex]]
[[Category: Flex]]
[[Category: ActionScript tutorials]]

Latest revision as of 17:48, 22 August 2016


Actionscript 3, the programming language shared by Flash and Flex

This pages is for actionscript concepts that apply to any ActionScript 3.0 authoring environment and any runtime that supports ActionScript 3.0. For the moment, two authoring environment are covered in this wiki, Adobe Flash CS3 and Adobe Flex. The focus of this page is on programming concepts that are completely tool un-specific (that would work in Flash as well as Flex).

Disclaimer

We write these pages as (recent) learners of the language. We are not experts.

EcmaScript Specification

ActionScript 3.0 is based on the EcmaScript 4th edition language specification. This specification can be viewed on the wiki of the Ecmascript Organisation. That specification also forms the chore of the Javascript 2.0 language contributed by the Mozilla foundation (see tamarin project at Mozilla.org).

Overview

ActionScript 3.0 is an object-oriented language for creating applications and media-content that can then be played back in Flash client runtimes (typically the Adobe Flash Player, more recently the AIR framework).

For those already familiar with a Flash authoring environment, it needs to be mentioned that quite important changes have been introduced in the ActionScript language between version 2 and version 3. Version 2 was somehow a scripting language targeted at unexperienced programmers. Version 3 has all characteristics of any serious programming language.

This may make it slightly more difficult for complete beginners to jump in. These changes, however, don't prevent a person who would have never programmed before to learn the language. This is in part because the authoring environment let you define content and basic actions without having to care about code. Progressive learning can take place.

The reason these changes were introduced is simply because the benefits of the changes introduced in version 3 far outweight any possible inconvenience to the complete newbie.

Two main aspects of the language:

  • AS3 is a strongly typed language. This means that whenever you use a variable, you must provide information about the type of data that this variable is expected to hold. If you want to use a counter and keep track of the counter progress in a variable, the type of data to be held in this variable will be of integer type (non negative numbers). To define that counter variable in AS3, you will type something like
var counter:int = 0;
  • AS3 is an object oriented language. This means that you have the possibility to split your code into specialized classes rather than write a single program of 3,000 lines of code. This contributes to make the code easier to maintain and easier to re-use. You can then design specialized components that will be re-used across different applications. A typical example of such a component would be a calendar object that pops up to let you specify a date.

Enough technicalities, let's program!

Whatever your level, make sure that you read the instructions on How to compile an AS3 program and that you are successful at compiling the first example given on that page.

Stage 1, Absolute Novice

What you need to get started. This assumes absolutely no prior experience with programming whatsoever. Because of this, it can be perceived as a bit dumb and slow-paced for persons who have already done some coding. In this case, simply rapidly browse through, have a look at the demo examples. Because each one explores a simple technique in isolation, they can be used as reference to Beginner and Intermediate coders.

Go to Novice

Stage 2, Beginner

This assumes that you have a very basic understanding of the general format and syntax of an AS3 program and know how to compile it. You know how to draw a rectangle on the screen by slightly adapting the code provided, but that's about it. You are a bit lost when it comes to writing your own program from scratch, even the simplest one. Well, you will be given the basic knowledge required to transform simple ideas into simple programs mixing graphics and interactive components. You learn about basic data types and control statements as well as how to use instance functions to organize your code more efficiently.

Go to Beginner

Stage 3, Intermediate

Drawing rectangles and interactive buttons on the screen is all good, but that doesn't get you very far, is it? Here you learn to write more complex programs, like mini-games. These programs are too complex to hold on a single page of code. You are introduced to the gist of some OO concepts. At this level, we have code spread over multiple files, class-based code organisation, inheritance, composition, dispatching events across objects, reading xml data or embedding assets stored locally.

Go to Intermediate

Stage 4, Advanced

All you need to know to write the next killer web 2.0 application that will make you rich or to become a professional freelance developer. You get to learn about design patterns and data services. The advanced tutorial will be shared between AS3 and Flex and would assume basic knowledge of Flex.

Well, this may remain underdeveloped till I reach that stage myself. Give me a few months. I challenge you to make more rapid progress than I will and actively contribute to the writing of that section!

Go to Advanced.

Resources

Related pages

Credits

This tutorial was for a good part written at a time where Marielle Lange (widged) was visiting fellow at the School of Mathematical and Computer Sciences, Heriot-Watt University (Edinburgh, UK). I am most thankful for the office space and collegial environment offered during my 3 months there.