00:00
00:00

As3: Oop 2007-05-04 23:00:26


AS3: Main

Introduction

With the arrival of AS3, a lot of focus have been put on Object-Oriented Programming (OOP).
You might or might not know it, but ActionScript has more than one programming methodology; procedural and OOP. Procedural is what most of you have been doing; it's when you simply write code sequentially on the frame... And OOP is when you split your code into several ".as Class files."

Now you might be wondering why you would bother doing OOP, well, I can think of one major reason: Organization. Now you might say; "well, my code is well organized," well, you could have well-organized procedural code, but it's never going to be quite as effective as OOP will make it.

Once you start programming in OOP, you will notice that you will perform better as a programmer; and it's not because you would have learned more functions, it's because you will be able to use the language in more depth than you ever thought possible. OOP will allow you to build up your code progressively whilst keeping all the various components separate. Personally, I like to compare OOP with a whole industrial process; for example, if you're building a car from scratch, first, you need to make the different parts for it, each part is quite independent and does different things, then, you put together all these parts to make the final product and interconnect them to make them work together... And that's your car.

Main

Ok, to start off this tutorial, you need to have flash open. From the main Flash menu, create a new .fla.

Now, the thing with OOP in AS3 is that you NEED to save your project and all .as files before you compile it... Now that's a GOOD thing, trust me! Also, I strongly recommend that each of your projects has its own folder (because a project entails mroe than one file).

Ok, so assuming that you still have your blank .fla open, save your file inside an empty folder on your computer name it whatever you like, it's not important.
Then, go to File -> New, and select "Actionscript File."

Now, you might or might not know about classes (other than the one that contains a teacher and students), so I'm going to tell you what they are: A Class is basically an Object-type in programming. So; Array, MovieClip, Number, Object, etc...
Basically, it's anything which you instantiate, either using the "new" keyword or through alternative methods;
To create a new Array for example, you just write:

var myarray:Array = new Array();
or
var myarray:Array = [];

a new Number:

var mynum:Number = 3
(you instantiate new numbers by using literals)

And in AS3, you instantiate a new MovieClip like this:
var mclip:MovieClip = new MovieClip()
but in AS2, it used to be like this:
var mclip:MovieClip = attachMovie();
or using createEmptyMovieClip or Duplicate (so there were many ways in which you could make a new MovieClip object)

Ok, but my point is that you have ALL used classes before; classes are just types for your objects; but you should look at them as "structured groups" of functions.

Now, a Class has a a structure to it, so, let's just get started and see what it is:

In your .as file which you created, write or copy/paste the following code:

package {
import flash.display.Sprite;
public class TheAwesomeSprite extends Sprite{

}
}

^ Ok, so that is the skeleton for pretty much all classes, but I'd like to explain what each part does;

package - Every .as file which contains a class needs to start with a package block, this is because, in AS3, you can have multiple classes in a single file. Now you can add a name after the package statement, just before the "{" but you don't need to wory about that for now. Basically, a package is a container for your classes.
import flash.display.Sprite - When you're building a class, you have to do a bit more work, if you code in the frame, this statement is called automatically, but in a class, you need to call it. What it does is tell the compiler that you are going to be using the Sprite class; now the Sprite class is a ligh-weight class which is basically just a MovieClip without a timeline; it's the equivalent of a movieclip with only one frame. I would suggest that you use it whenever you can. The Sprite class is situated in the "flash.display" package along with many other classes; such as MovieClip and BitmapData... If you want to import ALL the classes from the "flash.display" package, you can add a * in the place of the class name, so; import "flash.display.*"
public class TheAwesomeSprite extends Sprite - What this does is instantiate a new class called "TheAwesomeSprite," now at the end, you can see that it says "extends Sprite"; all this means is that "TheAwesomeSprite" IS a Sprite, but you can define extra methods (class-specific functions) and properties (like ._x, _visible, _y in AS2). In programming terms; "TheAwesomeSprite" is a "sub-class" of the Sprite class; it is just more specific version of it. Also, note the capitalization of "TheAwesomeSprite;" this is the convention which you might want to follow and I strongly suggest that you do so.
(Now, if you don't know what "public" is all about; i'll describe it at the end of the tutorial, so far, don't worry about it).

Now, what we need to do from our .fla file, is create an "instance" of "TheAwesomeSprite" Class using the "new" keyword like this: (please note that I'm using strict data typing)

var awesome:TheAwesomeSprite = new TheAwesomeSprite();

BUT... Don't compile yet!
You haven't finished to define your class's skeleton. (now, it wouldn't throw an error because flash player automatically manages the rest of your class's skeleton, but your class has no point yet; it's just exactly the same as a Sprite)
There is ONE more IMPORTANT thing that all classes which can be instantiated with the "new" keyword need; it's called a "constructor" function.

... Before I go on, I'd like to describe verbally what I want TheAwesomeSprite to do; I want it to be a blue circle with variable width.

Now this is getting exciting; the constructor is a function that is going to process any variables which you will pass to the class in this format:

new TheAwesomeSprite(argument1, argument2);

(this is like when you create a new Array("text",23,"hello world"); you're passing arguments to the contructor of the Array class).

Even if you don't have any arguments to pass to your Class, you should still have a constructor because you might need to execute some functions and set some variables for the instance of your class at instantiation.

Ok, so let's create that constructor; in our case, we're going to pass 2 arguments to our constructor; wid (width) and hei (height).

so, Here's the code now (go back to your .as file):

package {
import flash.display.Sprite;
public class TheAwesomeSprite extends Sprite{
function TheAwesomeSprite (wid:Number, hei:Number) {

}
}
}

Now, you have officially completed the skeleton of your first class (maybe).
Now, you need to know that the constructor is just a function that is called when you create a new instance of your class.

Ok, but right now, your class is still just a simple Sprite, but that's not what you want, you want your class to be a Sprite that is a blue circle. We need to implement the constructor to do what we want, so here is our class.

package {
import flash.display.Sprite;
public class TheAwesomeSprite extends Sprite{
function TheAwesomeSprite (wid:Number, hei:Number) {
super();
this.graphics.beginFill(0x0000FF);
this.graphics.drawEllipse(0,0,wid,hei);
this.graphics.endFill();
}
}
}

Continues Next Page…


Bla

Response to As3: Oop 2007-05-04 23:01:42


Ok, so you might have noticed, the super() call. What it does is call the Superclass (Sprite)'s constructor and passes arguments to it. But Sprite doesn't accept arguments, so we just leave super() empty; if out class extended an Array, however, we could pass any number of arguments like this: super("hi", "testing", 21, 56); and this would amount to the same as calling new Array("hi", "testing", 21, 56), but with your custom class' name instead; new MyCustomArray("hi", "testing", 21, 56). In reality, a call to super, just copies the super-class’ constructor statements to your custom class’ constructor.

Now, if you don’t need to pass any arguments to the constructor of the superclass, then you don’t have to call super(); flash player calls it automatically at runtime if you didn’t put it.

Now, where it says “this.graphics” it’s referring to the graphics property of your class. Note that in Class-based design, “this” always refers to the class the statement is in, no mater whether it is inside the constructor or any function within that class.

Additionally, you don’t have to include the “this” because Flash Player will assign the method to the class automatically, unless otherwise specified.
So basically, you just drew a blue ellipse with variable width and height…
Notice the “wid” and “hei” variables in this.graphics.drawEllipse(0,0,wid,hei).

Now the first parameter is the x, second is y, then comes width, then height… now if you look back at your constructor you can see how we set up “wid” and “hei.”

function TheAwesomeSprite (wid:Number, hei:Number) {

What this does is that whenever we call “new TheAwesomeSprite()”, we HAVE to pass 2 arguments to it: the first one will be stored in the “wid” variable and the second will be stored in the “hei” variable.

We can then use these variables inside the function which receives them (which in this case is the constructor).

So, go to your .fla and where you wrote
var awesome:TheAwesomeSprite = new TheAwesomeSprite();

And add 100,100 inside the ( ) so:
var awesome:TheAwesomeSprite = new TheAwesomeSprite(100,100)

Now, in AS3, you need to ADD your displayobjects to the stage, so go:

stage.addChild(awesome);

again, this goes back to what I was explaining before; you don’t NEED to have the “.stage” part because flash player automatically calls the method on the class in which it is in… And when you’re coding in the frame, that is the stage. So you can just write:

addChild(awesome);

Ok, so test and run your flash… you can play around with the numbers if you like.

Now, go back to your .as file and look at the declaration of your constructor:

function TheAwesomeSprite (wid:Number, hei:Number) {

What if you only wanted the parameters to be optional?

It’s easy, all you do is set default values to the variables in case they are not assigbned anything;

function TheAwesomeSprite (wid:Number = 50, hei:Number=50) {

This means that if we call a new TheAwesomeClass() without having any arguments, if will create a circle of 50*50 by default.

Ok, to finish this tutorial, I would like to mention “scopes.”
There are several basic scopes in AS3:

public, protected, internal, private.

You only need to worry about 2 for now:
public and private.
When you call a method (inside a class file) public, it means that it will be accessible from outside that class. If you define a method as private, it means that it is only accessible from inside the class itself, it can’t even be accessed by subclasses! So if you call it from the frame, it will not work.

protected is half-way between public and private, you cannot call it from the frame, but you can call it from a sub-class.
internal means that it can be called anywhere inside the package block but not from outside or from a subclass.

Now, there is more to OOP than this, and I might make another tutorial to follow on this one, but I hope that you have gained a lot of knowledge from this and hopefully, you’ll figure a lot of stuff by yourself :)

Cheers.


Bla

Response to As3: Oop 2007-05-04 23:13:41


Great tutorial! A perfect addition to AS3: Main.


Asus P5Q PRO, Intel E8400 @ 3.60 GHz, 4GB DDR2-1000, ATI HD4850

BBS Signature

Response to As3: Oop 2007-05-04 23:15:33


Awesome tutorial. Wow. Unbelievable, thank you, I understand that a LOT better now!

Response to As3: Oop 2007-05-04 23:21:25


Alphabit you are a god. Whens the AS3 3d tutorial comin? ;P

Response to As3: Oop 2007-05-04 23:22:33


At 5/4/07 11:15 PM, RPGBandit wrote: Awesome tutorial. Wow. Unbelievable, thank you, I understand that a LOT better now!

Thanks!
I'm glad it helped.
I guess that once you start learning OOP, you start to understand why things are a certain way and it makes everything seem easier.


Bla

Response to As3: Oop 2007-05-04 23:29:29


At 5/4/07 11:21 PM, PrettyMuchBryce wrote: Alphabit you are a god. Whens the AS3 3d tutorial comin? ;P

Hehe, thanks.
I think I'll wait a while before making a 3D tutorial; It'll be better to wait for people to grasp the basics before getting into some hardcore stuff.
I believe that stuff like OOP is very important for making 3D applications; they are so complex that you need to be able to separate components.

On a side note, I found a method to make 3D without using vectors... I didn't know it was a big deal, delta kind of pointed it out lol. I think it gives the developer more control, and it's easier to implement too... Probably a bit slower though.


Bla

Response to As3: Oop 2007-05-04 23:38:21


I would like to add something in regards to packages.

The name of the package is essentially the name of the folder it is in.

So say you have your classpath set to C:\myGame

Packages that are located in that folder are not named. They are just simply

package {

}

Now say you have a package called com.classes.examples

It would appear like this:

package com.classes.examples {

}

But here's the catch. It *MUST* be located in this folder:

C:\myGame\com\classes\examples

I hope this helps. It's a really nice way to organize things.

Response to As3: Oop 2007-05-04 23:44:09


BTW, giving packages names and unique folder structures allows you to have two classes with the same name. With two different packages, you can have this:

com.classes.examples.MyClass
com.classes.MyClass

Both classes have the same name, but are different classes and do not conflict with each other. This is acceptable.

Response to As3: Oop 2007-05-04 23:56:33


At 5/4/07 11:44 PM, ShooterMG wrote: BTW, giving packages names and unique folder structures...

I was going to add that in another tutorial, but that's fine.
I still haven't looked at methods, properties and variable scopes, so I'll just focus on them.


Bla

Response to As3: Oop 2007-05-04 23:59:06


Sorry :P Just trying to be helpful

Response to As3: Oop 2007-05-05 00:03:43


At 5/4/07 11:59 PM, ShooterMG wrote: Sorry :P Just trying to be helpful

That's ok, I don't mind, it actually saved me some time. No need to apologize.
If I forgot to mention anything which you think deserves a place in this tutorial, then I encourage you to post it here, because it probably does :)


Bla

Response to As3: Oop 2007-05-09 00:57:16


Im having trouble including the package/class that is in the .as file. I get an error saying "TheAwesomeSprite" is not a compile time constant. How do I include this class in the fla?


BBS Signature

Response to As3: Oop 2007-05-09 01:03:56


At 5/9/07 12:57 AM, rgourley wrote: Im having trouble including the package/class that is in the .as file. I get an error saying "TheAwesomeSprite" is not a compile time constant. How do I include this class in the fla?

Locate the folder that the .as file is in, then in Flash go to edit, preferences, actionscript 3, then add that folder location to the classpath. Then in the .fla, just type

include your_file_name_here;

Response to As3: Oop 2007-05-09 01:11:02


Thank you, but now im gettin a string literal expected error, so i tried putting it in quotes "myFile.as", but then i get a packages cannot be nested error.


BBS Signature

Response to As3: Oop 2007-05-09 04:10:56


At 5/9/07 01:11 AM, rgourley wrote: Thank you, but now im gettin a string literal expected error, so i tried putting it in quotes "myFile.as", but then i get a packages cannot be nested error.

You don't need to include the file. You only need to import it if it's in a difference directory. Otherwise, if the .as is in the same folder as the .fla, you can use the Class directly without importing anything.


Bla

Response to As3: Oop 2007-05-09 08:55:54


Okay well, I have the .as in the same folder as the .fla, but I keep getting a compile time constant error. For some reason it isn't reading from the class.


BBS Signature

Response to As3: Oop 2007-05-09 17:43:56


I still can't get it to work. Any help would be greatly appreciated.


BBS Signature

Response to As3: Oop 2007-05-09 18:20:54


At 5/9/07 05:43 PM, rgourley wrote: I still can't get it to work. Any help would be greatly appreciated.

Is your file named the same as the name of the main class? i.e.

MyClass.as

package {
public class MyClass {

Response to As3: Oop 2007-05-09 18:28:25


Awesome thanks. Didnt know that i needed that. :D


BBS Signature

Response to As3: Oop 2007-05-18 09:24:55


That was great! Very easy to understand, great job.

Response to As3: Oop 2008-03-22 11:23:25


Little help please :P

//Shark.as
package
{
	import flash.display.MovieClip;
	public class Shark extends MovieClip
	{
		public function Shark()
		{
			var Shark:MovieClip = new MovieClip();
			addChild (Shark);
		}
	}
}

//Main flash (.fla)
var shark:Shark = new Shark();

I want it to add Shark to the stage, no such luck though :(


BBS Signature

Response to As3: Oop 2008-03-22 13:19:26


bump...


BBS Signature

Response to As3: Oop 2008-03-22 13:23:05


addChild(shark);

Response to As3: Oop 2008-03-22 14:12:45


//Shark.as
package {
	import flash.display.MovieClip;
	public class Shark extends MovieClip{
		public function Shark(){
			var shark:MovieClip = new MovieClip();
			addChild(shark);
		}
	}
}

//Main flash (.fla)
var shark:Shark = new Shark();
addChild(shark);

BBS Signature

Response to As3: Oop 2008-08-18 05:44:10


Thanks for this great tutorial =)

Response to As3: Oop 2009-07-18 13:16:42


Thankyou! Another step to understanding OOP!
:) :) :) :)


I love xbox live and I like flash games too!

BBS Signature