Flash Essential

AS3 Classes Beginners Guide Part 2

May 28th 2008
11 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



11 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.

  10. marie

    Thanks so much!!!!!!!!!!!!!!

Leave a Reply

maniacs preachers
1 18 scale aircraft
amy larson attyorney indio ca
coco and ice tee
1 banking golden online
andorra playa de las americas
high perfomance house greencraft
1908 studios
jacqueline and leo perry
12vdc to 9vdc lighter plug
amazon prebook harry potter
dr william rigby
100.5 fm atlanta
riotkayaks.com
la mujer de mi hermano
lyrics to chopped and screwed
christopher plummer i
fireconcepts.com
crowne at razorback
agenda hsie
ab slider
culligan man
a t ireland
slcentral.com
holistic puppy by susie
dr hahn tomball orthopedic surgeons
anthony wayne school and bullying
13799 commerce parkway richmond
celtic masonry in nj
1998 chevy s10 lambo doors
roseanne cash brain surgery
dog sniffing poop
are wood square floors durable
croatian letter writing
black and white dragonballz pics
enzo angiolini sandles
chineese flute
digitalhymnal.org
ala acrl events amp conferences
isafreedom.com
consequences for children
2007 international quilt festival houston
avenues bistro brookside
bert ott
afro american life and history
datetheuk.com
linux logitech quickcam chat
gabrielle carteri pictures
100 compression golf balls
css cursor
advanced health media lose pfizer account
combination traffic and pedestrian railing
aduiepyle.com
2001 pontiac grand am manuals
how tp make a candy bouquet
brown spotting during second trimester
arthritis psoriasis hair loss
bird cronin maternity si belt
mandarin leaf discoloration
guitarimports.com
marginal do rio pinheiros
johnys selected seeds
1986 mazda parts
voaautoauction.org
call of the horned piper
1 4hp stud motor dallas
job software engineer oracle ahmedabad
allied veterans cyber center
nat pmp said
delete file on reboot
advertising is not responsible destroy world
oldworlddistributors.com
atichoke arrangement
santander consumer bank
102.1 the edge dallas tx
1990 audi 100
lampshade bands
cfl vs metal halide
britney spears hot fotos
basis of western institutions
april 2007 frost in mo
cuny nursing schools
afghanistan abduction
african themed ceramic tiles
4chan lists site
gartner 2006 mentoring
dailey news record harrisonburg
art-customer.net
clip movie singapore tammy
balkan pictures archive military photos
arnold chiari ii expectations
cancellations hotline
walkerschools.org
opel 15727
bournemouth international conference centre
applesauce and oatmeal muffin recipe
oregon wic program
business recommendations on disney
account free join
astrology gemstones
buying a car in shanghai
a4 style buttstock for ak
aussie amber
antique needlework pattern
controlling antibiotic induced diarrhea with loperamide
philadelphialiving.com
1980 kawasaki kx 125 gas tank
appliqueing quilts
acc countdown with kix brooks
federated garden clubs of conn
city office riga
19th century wagons
webspheria.org
activities for listening speaking
flagstone floors
aussie gas grill koala
acme boots
spoletousa.org
bale bundles
soccer.ru
c tic tac toe vector
alice 96.7 fresno
gary fackrell hooper
antique finishing furniture
2327 malcolm
travelsdc.com
c c cylinders
aloha aina wellness center
amy buchanan michigan
facilities maintenance soo
amanda macdonald sherwood park
ancient scottish dresses
book of quotations
preplogic.com
waterside holiday park
citgo lite
airline tickets kingston acc fic
hugh jackman michael caine
longs furniture company indiana
apple cider tablets
cabins in pagosa colorado
cca division of taxation
canine lymphoma cure
gleevec.com
cemeteries dartmouth halifax nova scotia canada
animal stacks
duty suppression of fact
frisbee golf washington
venicesuites.com
anglo irish war perspectives
kwik kamp parts
20 facts volcanoes for kids
1999 keystone cabana trailer
muppet closing theme song instrumental
aeroquip distributors in corpus christi texas
1103 silas creek parkway winston salem
shemale-dick.com
bonney lake cao
bridal elegance salon
how to build a sandbox
emma barnum california
news alerts zdnet services companies
blackburn cathedral uk
gbm tumors thc
bluevelvetvintage.com
consumer perception of southwest airline
5 bedrooms lrg lot outside citylimits
a white heron setting jewett
workoutpass.com
schoo closing cadillac mi
handpainted porcelain religious medal
australian composer katy abbott
marisa del portillo feet
1982 honda goldwing gl 1100
argenine citroline vitc vit a
black leather spike dog collar
lyrics sweet tangerine gold
crayon holder
invader zim myspace graphics
alfredo escondon ca
belvedere saugatuck
cd dvd protectors from scratches
bakersfiled brazilian jiu jitsu
2mp ic usb camera chip
armstrong professional thinwall flutes
trillion diamonds in anniversary band
jaymen ooh la lishious
back ground of scooter libby jury
chronicles of narnia review
barbara lahr chambersburg pa
1948 ford f100 truck parts
about ask com binoculars faq
bigtitvideoclips.com
happenings tidewater
dr james alpheus seaman brooklyn ny
australia gdp
2000 ford ranger troubleshoot
acquire shares press release
42 x 42 receiving blanket
dance dance revolution un deux trois
bridgeport barnum festival
cheats for def jam vendetta
gemini love a sagittarius
doncaster interchange
creating excel spreadsheets
canon in d in indie music
pudcat.com
1996 sea-doo spi engines
jennie dugan concord 1805
enlargementgum.com
ally aj potential breakup song lyrics
2 hot twins 2 bang
astronaut space traveler costume
ecc leg cuffs
blanche dubois illusions
1940 s cocktail dresses
bowles indian territory
dogs and hips
cytochrome p450 1a2 enzyme testicular cancer
arctostaphylos uva-ursi point reyes
georges du tam scouts
1960 a time of change
girl killed in hoboken
benedito jos nascimento
bryants poems william cullen bryant
bermuda coco reef
pavillon puebla
pathologist career
ellicott city porcelain fillings
alla and lotr and forums
csrs offset confusion
adelaide dutton
american baby childbirth educator conference
nudewear.com
irritation of the liver
download epsilon 2nd movement
191 cessna plans
gayhardcoreporn.net
linkin park chords faint
athens tech faculty
half price hookers
bayfidan 250 ec
peritoneal cavety
dcr engineering
56k modem hourly transfer rate
cimetidine induced apoptosis
aromatase inhibitor bodybuilding
heel bursa and treatment
buick rainer v-8 reviews
1837 cherokee war 2nd georgia militia
jenni bick coupon
americanfence.com
astrology cancer pisces decendant
albino doberman
buy clothing from hm online
buffalo psychiatric center history
altair advisors
1977 trans am review
natureandscience.org
copiers and air quality
scatkingdom.com
barbara in hebrew
frys eletronic
candlestick cassia
38181 memphis tn
1977 ford brakr caliper brackets
susie orman retirements
a1worldwidelimo.com
army spouse discussion board
desi anju bhabhi mms clips
final fantasy xii gamesharke codes
address find name people
accessing lawsuit risk
choosing a cavalier king charles spaniel
dunbar associated
usfcu.us
greenleaf inc
3ft antenna tripod
quilt-this.com
ed mcmahon next big star
financial advice cambridgeshire
action item sheet
messagebot.com
alfredo baena jr
hd limitation on tc1100
teeny bopper club cindy crawford
breastgirls.com
homestead pools lewistown pa

arkansass democrat gazette classifieds may 2008
at t tilt downloading music
carbon dioxide combustion pe polyethylene
buyuklericin.net
a speech about immortality
invincible 1992 namibia
answers for self evaluations
how to make clothing in morrowind
buy squid beak
jem lyrics 24
bcpassport.com
bally doyle pub downers grove
24 volt lawn mowers
geniimagazine.com
100 greatest villains
l5 s1 herniation loose stools
lowest price on s2 jago
wholesomesweeteners.com
anjelica sinn tennis court mpeg
11 alive news west palm beach
1080 video fireplace
used yanmar vermont
bamboo camouflage boot
dui defense plea
date palm phoenix dactylifera taxonomy
blue da ba dee eiffel 65
alternativa grupo
cbscompanies.com
1965 churchill token
lombardi inn oh
skoar.com
aar comments for presentations
100 ways to praise a child