Flash Essential

AS3 Classes Beginners Guide Part 2

May 28th 2008
10 Comments
respond
trackback

In Part 2 of our Classes tutorial series we are going to take everything we wrote in Part 1 of our Class tutorial and add to it. We'll create a reusable class that will scale objects when you rollover it with your mouse.

Part 1 of this tutorial

You can view the finished class Here

Step 1 – Extending Our Class

After FirstClass remember that’s the name of our file and also our class name we type Extends MovieClip. What this does is FirstClass takes everything from the MovieClip Class and adds to it.

package
{
class FirstClass
{
function FirstClass()
{
trace(”This is my first Class”);
}
}
}

Step 2 – Adding Our Import Statement

Inside our first package bracket we have added an import statement. This import statement brings in all the information about movie clips, if we didn’t have this line we couldn’t extend the MovieClip Class as flash wouldn’t know what we are doing. So whenever you extend any class in an external file make sure you import that information using an import statement.

package{

import flash.display.MovieClip;

class FirstClass extends MovieClip{
function FirstClass() {
trace("This is my First Class")
}
}
}

Step 3 – Adding Methods

A Method is a Function that is attached to an object. We write our Method after our Constructor Function. We start by typing function, then we give it a name, and finally we type void at the end because we aren’t returning any values. We then type what we want our function to do inside open and closed curly braces just like we’d do with our Constructor Function.

So essentially a Method is just a Function inside a class, for example in the code below only FirstClass can run myFunction.

package{

import flash.display.MovieClip;

class FirstClass extends MovieClip{
function FirstClass(){
trace("This is my First Class")
}
function myFunction():void{
trace(“My Method Works!!!”)
}
}
}

Step 4 – Public and Private

When defining Classes, Methods, Variables inside of a class file you need to specify if it’s known to the class or of its something that you can call or modify outside of the class.

We do this by using Public and Private (explained above). Before our class definition and our constructor function type “public” this now means properties are accessible within the class as well as from instances of the class. Before our Method type private, this now means the properties are private when they're accessible only within the class.

So To Clarify;

private

Properties are private when they're accessible only within the class.

public

Properties are public when they're accessible within the class as well as from instances of the class (or directly from the class reference when declared as static.

Your code should now look like this;

package{
import flash.display.MovieClip;

public class FirstClass extends MovieClip{
public function FirstClass(){
trace("This is my First Class")
}
private function myFunction():void{
trace(“My Method Works!!!”)
}
}
}

Step 5 – Lets Make Something Useful

Now we are going to build this class into something we can use, we are going to create a simple class that scales an object when you roll over with your mouse. So we'll first add some Variables in the next step to get us started.

Step 6 - Adding Some Variables

Inside our Constructor Function we are going to add some Private Variables inside our class definition before our Constructor Function. We'll name our variables Xscale and Yscale and set the data type to number, these variables will represent the original x and y scale of our Movie Clip.

Your code should now look like this;

package{

import flash.display.MovieClip;
public class FirstClass extends MovieClip{
private var Xscale:Number;
private var Yscale:Number;
public function FirstClass(){
trace("This is my First Class")
}
private function myFunction():void{
trace(“My Method Works!!!”)
}
}
}

Step 7 - Inside Our Constructor Function

Inside our Constructor Function we'll add some event listeners but first take note of what the this keyword is below. We set our Xscale and Yscale variables equal to the scaleX and scaleY properties. We then add some mouse events and give them the names bigger and smaller.

The this keyword is a references to a method's containing object. When a script executes, the this keyword references the object that contains the script. Inside a method body, the this keyword references the class instance that contains the called method.

Your code should now look like this;

package{
import flash.display.MovieClip;
public class FirstClass extends MovieClip{
private var Xscale:Number;
private var Yscale:Number;
public function FirstClass(){
Xscale = this.scaleX;
Yscale = this.scaleY;
this.addEventListener(MouseEvent.ROLL_OVER, bigger);
this.addEventListener(MouseEvent.ROLL_OUT, smaller);
trace("This is my First Class")
}
private function myFunction():void{
trace(“My Method Works!!!”)
}
}
}

Step 8 - Mouse Event Functions

Now we give our mouse events some functions. So first get rid of that myFunction and it's trace statement and we'll create some new functions called bigger and smaller. We'll give our bigger function some properties first, inside our curly braces we are multiplying our scaleX and scaleY values by 1.5. and Inside our smaller function we have are returning the object to its original size.

package {
import flash.display.MovieClip;
import flash.events.MouseEvent;

public class FirstClass extends MovieClip {
private var Xscale:Number;
private var Yscale:Number;

public function FirstClass() {
Xscale=this.scaleX;
Yscale=this.scaleY;
this.addEventListener(MouseEvent.ROLL_OVER,bigger);
this.addEventListener(MouseEvent.ROLL_OUT,smaller);
}
private function bigger(event:MouseEvent):void {
this.scaleX*= 1.5;
this.scaleY*= 1.5;
}
private function smaller(event:MouseEvent):void {
this.scaleX=Yscale;
this.scaleY=Xscale;
}
}
}

Step 9 - Lets Test It Out

Click File New and create a new Flash File and Save it. Once you have done that Select the Text Tool and type out Home onto the stage and convert it to a Movie Clip, call it mcHome. Open up your Library Panel, right click the mcHome Movie Clip and select Linkage. In the dialog box check Export For Actionscript and type in the details below.

linkage gif

We have our Actionscript File as our base class and our Movie Clip as our Class. You can create more Movie Clips on the stage and link them to the same AS file using the method above. Press Ctrl Enter to test the movie.

Conclusion

Congratulations you have created a useful class that you can reuse whenever you want! I hope this tutorial has helped you get a better understanding of how useful classes can be and how they can be a great time saver.


This post is tagged ,



Sponsors

Explore Recent





Monthly Archives



Friends and Affiliates



10 Comments

  1. Fred

    "function FirstClass{" should read function "FirstClass(){"
    the braces go missing halfway down…

  2. admin

    Never noticed that, cheers Fred.

    No idea why I missed it.

  3. Jim

    In the above example it does not state specifically what the Constructor Function is. It should be noted that if you have as shown above "public class FirstClass extends MovieClip" then the Constructor Function is the function that has the same name following the word class above. Meaning the Constructor Function is the function FirstClass. So FirstClass is the Constructor Function.

  4. Radrad

    "1046: Type was not found or was not a compile-time constant: MouseEvent."

    can someone help me out what does this mean? :)

  5. mcgiggle

    it means, redrad that you didnt import the mouse events, to do so, go within the package container before the class declaration and add this line :
    import flash.events.MouseEvent;

    and itl solve that error , cheers

  6. Thanks!

    This was very helpful for someone like me who wants to get into classes.

    Thanks again

    Tiaan Prinsloo

  7. Jody,

    Nice writing your tutorial on reusable classes!
    (http://www.actionscript.org/resources/articles/698/5/Make-your-own-reusable-classes-using-Flash-and-AS3/Page1.html)

    I would like to consider myself an intermediate AS3′er. Much like yourself, I started getting involved with AS because I was inspired by the work of others and needless to simple tasks yielded to more complex ones and i have been addicted to learning AS3 ever since.

    It's even inspired me to go back to school and get a degree in programming. So not only do I have experience with AS, but I'm learning Java as well. My biggest hang up has been classes. No one, including my professor and countless online "googled" tutorials, has been able to explain thing in english. Your tutorial, really made thing click and I just wanted to extend a huge thanks. I see my code being less spaghetti in the future!

    You also couldn't have demonstrated with better topics of keyboard control or drag/drop- two things i use quite often and am tired off re-typing or copy and pasting over and over! You also did a fine job explaining everything and didn't not making assumptions about what the reader may or may not already know. It was all there.

    What I find with other tutorials, the problem is that they are written by experienced scripters who forget that what's now "easy" for them isn't "easy" for us novices. You hit the hammer on the head.

    Again, thank you for your tutorial and taking the time to write it!
    `Chris Shields

  8. 10x MAN,

    The first tutorial I understood even that I'am a pretty good programmer in C and C++.

    10x a lot again.

    Goran

  9. Digital Eagle

    I loved your tutorial, very clarifying, and yes!, your method works. Thanks for sharing your knowledge.

Leave a Reply

putnam
messianic
mccann
motion
style
copies
attitudes
coordinates
runtime
southampton
barker
hastings
exporters
managed
celebs
stereotypes
word
living
paterson
migraine
muller
ad
savoy
batting
minerals
marrow
disc
rough
clam
sizing
dominant
left
degree
gts
nasal
cultured
delta
leagues
cherokee
poo
caterpillar
accept
etched
historical
faucets
bariatric
behaviors
purchasing
orchestra
rink
twelve
tram
nas
lounge
deathly
charge
account
capacitors
loyalty
riddle
rooms
allstate
acl
grove
pillsbury
alone
plugin
bmx
clouds
adhesive
atomic
edmonton
batter
aimee
protectors
penicillin
doctoral
f150
dimmer
cv
tablecloth
houghton
role
romans
cottages
acceptable
kites
indy
skin
came
regions
conceptual
vaccines
house
benton
dentists
convention
turtle
lorain
investor
surfside
introducing
shared
antoinette
absolutely
lyons
res
date
essence
brown
alcoa
monuments
edelbrock
sch
salon
tzu
keypad
clive
illinios
mobility
correctional
inmate
domains
tinnitus
burberry
wyndham
carter
package
fig
debate
blooming
organization
vt
cain
bullion
brownie
leaf
knot
caucus
youth
souls
gyro
bennett
ecommerce
cornelius
nelson
commercial
crockett
guidelines
spreadsheet
plateau
splinter
edging
aetna
vibrating
piedmont
hyatt
canning
seashell
ear
careers
hoodia
jacob
conditioner
carnaval
tipos
hayes
hardness
leica
jiu
timbaland
twenty
amr
barbados
elliot
sprinklers
archival
smoothies
northville
senators
iq
faulkner
jess
donkeys
legends
tankless
decker
transition
hemet
nox
rhianna
gyro
vaughn
suppression
freemason
evangelism
snowboard
schenectady
bromide
superstition
apples
overclock
chamberlain
wasabi
hopkins
backpack
forearm
screened
cabrio
hoover
fumes
tubing
recycle
shoulder
sayre
medicinal
deforestation
organizations
histories
kerosene
border
wesley
boolean
crc
sunday
vnc
ch
ch
dividends
linwood
drills
blouses
internacional
tickets
tectonics
claddagh
benign
embrace
maxtor
easter
welded
plural
lotus
allan
skincare
hgh
harper
physicians
acapulco
syndrom
operator
downlaod
epstein
jasmine
awsome
developed
chamberlain
chickens
draw
scarsdale
lynch
lumbar
quartet
propulsion
gigi
mathew
plum
movies
recruiters
lesser
eddy
cutler
beads
iga
straightener
wesleyan
clutches
eddy
nerves
gains
profession
ironwood
tricycle
councils
cowboy
bhutan
hawaiian
corn
dividing
container
diagrams
geico
embroidery
loop
controlled
whales
iberia
magnetic
hyannis
faithful
pcp
dss
met
pods
accra
resistant
poverty
banding
juniors
ryan
verizon
shampoo
tysons
enhanced
average