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

auto battery discharge cold
blake holman sioux falls sd
ameican pitbull terrier
character story elements powerpoints
construct a wheelchair ramp
paralysis.org
bangladesh orphanages
2000 lb bomb
kristi rowley
concrete acid etching supplies
bossier city la real estate
bedford indiana job openings
cordura bags 2008 hayabusa
hana kimi direct downloads
07 tahoe lug pattern
stroke-jobs.com
2008 satilite map
arctic zone lunch bag
04 g35 body kit vader 3
blackpool town fc
reserved sugar
animal control in evansville
1927 roadster
myspacelayouts.net
cast costumes for hello dolly
art for the heart fundraising
treesforyou.org
agape gaddis
1080p 24 lcd monitor
etymotic.com
article about dpms lr 308
27713 nc zip code
boo creepy foot doctor
convicted offenders listed in british columbia
daybed covers toile
job predict
butas sa pinto silipan
0 andreas test residence
foxpro serial port fll
dr natura and oldest man
2000 mercury sable too lean
frozen liquid longest
2003 exotic spices calendar
1 bedroom suite orlando
1 2 inch vinyl micro blinds
colleges that teach veterinarian toxicology
dieter klimm germany
3 cm dialated
captain william fowler
mmahq.com
1st lady on my
ancient mayan popol vuh
pinky and the brain avatar
claire pruitt doll patterns
xbux.com
av 2009 virus blocking malware bytes
2002 mountain aire 4097 floorplan
emeritus restraint policy
arizona diamond backs fan club
ftd florists oneida ny
courier service pretoria rundu luanda
insane clown posse downloads
bello pr-25 review
4 bedroom rental in yorba linda
5 estacion flores de alquiler video
americus vespucius
ati modified driver vista 32
adoption paralegal in toronto
dish pvr 501 mod
1800 daniel brothers in tn
irony.com
dominant bodybuilding females
custody911.com
adm buyout
alex moulton mark 1
hughesspeednet.com
byron hinton
shoehunting.com
experiment on rl circuit
1296 mhz power amplifier circuits
7th level of hell survey
constitutional class
anemia and skin itch
goofy gold download
webshapes.org
car jacks 3.5 ton costco
neopostinc.com
brookfield athletic shoe company inc
cause transaction lagging bank reconciliation
fire at mann gulch
ambridge duck hunting
application coding wikipedia
12 1 2 womens cowboy boot
cci cb short
before the hammer strikes the nail
interpretation of low oxygen saturation
autosearch.com
outrigger condos
carl erickson pole vault camps
matchmaker pittsburgh pa
cheats gba pokemon emerald
and eminem forgot about dre
howtomaketime.com
andorra property
1939 indian scout timing specs
diet plans for chronic indigestion
applied kinesiology for hiatal hernia
read socrates in love online free
nutone-home.com
air europa seating arrangements
8 configuration sacral fracture
assfucked to tears
alto sax 575 allegro
geological features in the appalachians
bill clinton comment obama
addicting games territory war
irc mythos cx slick 700x42c
msn messenger signup
kissed his feet bet
apache2 debian etch amd64
bnvillage.co.uk
do horses have treat preferences
10mb network
cantv.net
noel chance racehorse winners at warrick
cmu waterproofing techniques
brenda adams bebo
1967 ford shelby mustang pics
charlotte witt
13th century mens clothing france
embassyhomepage.com
blood draining out nasal passages
sprinklerfitters669.org
stephan a rhodes
cemeteries in holyoke ma
gallstone purge
emma tryon
amboy washington mptels
branson ultra sonic cleaner
anti-tank obstacle
chris mcgee
auto dealers mit
belle meade united methodist
hotel regent paris
smdailyjournal.com
1995 ford f150 sputters on acceleration
dan sommer in omaha nebraska
academy of our lady chicago il
accrual method 12 month membership
1941 luger manufacturing plants
curry mussels
construction-business-forms.com
gym clothing catalogues in south africa
american portrait painter a jacobsen
hotels in patagonia
but seriously folks joe walsh
address of lima polo club
william butler yeats home address
another instance of voice platform genesys
bonney m stille nacht
former french canadian provinces
creole echoes excerpt
seekingxxx.net
gods goddesses
100 reason stop smoking
all-about-style.com
andre d sparks
map of the westward expansion
examples of meta search engines
aluminum sliding glass door lock
brattleboro vermont nakedness
2008 norton update problems
betty joyce harrison
panasonic.net
7th grade science dothan al
clearwatertribune.com
age of consent in nc
nineteenth century cultural stereotypes
smt contract manufacturing at elgin il
20mn.com
avian immune
arresting or reversing foot neuropathy
citalopram actavis pirist v l ke
netinfo.bg
1929 cadillac imperial
mikesradioworld.com
anatomical mold
12 days of christmas gift ideas
asx-200bx lan
gaydadsandyoungersons.com
isabella fiore let love reign purse
allow interactive logon to workstations
computer sent received meter
amicroe ready boost usb drive
augustinespiritualgoods.com
basilica di bologna
cj fitzgerald
chicks in sturgis
buenos aires art supplies
password protect folder sme server
australia port fairy accomodation
chantal hensley
ariston dishwasher
2009 liturgical year
soundproofwindows.com
absent cells on pap
gold rush miners in california 1852
content for newsletters
academy countdown leader
craaigslist.com
air race reno 2007
pdfsoftwarecenter.com
desert crepes
battlefield 1942 home page
assignments on employee made by organisations
a taste of thai instant meals
custom stainless products etobicoke ontario
a w d hammond ltd website
frcp exemptions
albums released in 1989
2wire router problem wii
amanda marie gould
greek writing utensils
child abuse coppell texas
snappysoftware.com
jillian barberi
keeler hydraulics
install fedora on mac powerbook g4
exoticagirls.com
cakewalk music creator crossfader
cats beta carotene treat tylenol toxicity
norterrashopping.com
american culinary wagner ware wholesale
belinda jensen autobiography
ben hogan golf tips
concave and convex
antelope complex fires in the west
alan dresner and natalie
bluetooth setting cingular t616
adolf hitlars childhood
endorsement for your friend
artificial intelligence checkers
albright on ot phoenicians
label stuck in tde laminator
aimpoint style reflex sight
brook skye video
contemporary perspectives in writing
acmediy.com
franconia sami fakhouri
custom shower curtains with longer lengths
sacramentorealestatevoice.com
express scribe dss problems
air travel carry on rules
abraham lincoln association
bilingual baptist minister indianapolis in
atomic absorption spectrometry free book welz
bacon club t-shirt at journeys
1700 hemlock oxnard
a little pain tabs nana
40th birthday rhymes
ahadees.com
brookside equestrian centre kitchener
adanal roofing langley bc
h clinton supporters
burning crusade
1760 59th avenue sacramento ca 95822
atkins beach diet south vs
bible xml
elder david pennington
1903 legare circular sock machine
asparagus baked wine
1911 22 rimfire conversions
191 2nd avenue cochrane ontario
agatha christie novels online
american pledge
bellcad.org
circut city rebates
crater lake green outcropping
condos townhouses new bern nc
download stairway to heaven
bed robe
adobe epic app cannot be launched
11x17 4c process preliminary poster examples
daytime emmy award talk show
burley samba
char-broil rotisserie
adoro las es liebe sein
homosexuality umass amherst
100 cc suzuki sv
birch carrol cinema townsville
1973 firebird radiator support
sandia memory gardens
probeindustries.com
fumani dialect
nacelink.com
avalon title ltd mclean virginia
farwestfamilyservices.com
antwerp cut diamonds
dino van eeckhaut cairo appointed sofitel
dosha.org
2008 sport touring
bleeding doge truck breaks
johnnycrosslin.com
24071 desert drive florence az 85232
bioclusive overlay
areas effected in 2007-2012
geography hottest part of the world
aikenregional.com
antarctic centre new zealand shop
coupons for amazon purchases
add affiliate link program
alicia keys samsonite man
saltlaketribune.com
accessory lady
aboutlilacs.com
banner insurance rockville md
elvi fashion stockists uk
federal govt
nalco.com
ankle fracture lower extremity
beloved sisters mc
alisha lanier
cindy ziegler re max of wasilla
32 degrees mesa watch
beat the clickbank competitors
audi a4 fuse changing
adjusting bernina 1001 bobbin tension
australian olympics bike riders
cheap las vagas limos
pulmicortrespules.com
1611 bosch power tool parts breakdown
12 ci engine hp
articles about human resource managment
cal state university pomona anthropology
buses into motorhomes
international tae kwan do karate federation
ana and muscle antibody
dav pilkey biogrpahy
12 week old boxer puppy photos
5 interesting facts about scallops
darnell crisconi
foxfire banjo
4gazebos.com
research terrestrial orchids
cloudster.com
allergic reaction to dust
hickoryortho.com
lexis nexus herb
milky cat torrent
comprehensive-kidney-facts.com
b strep symptoms
07 ford mustang gt
waterfrontbluesfest.com
antique wardrobe trunk pricing
banana fana fo fana
856 edi invoice