Tag Archives: AS3 Pitfalls

AS3 Pitfalls – SOUND_COMPLETE Event is Not Firing

PROBLEM:

The SOUND_COMPLETE event is not triggered when your sound finishes playing.

SOLUTION:

There are a few different reasons why this problem may occur, but here’s how it played out in my project:

When you’re listening for a SOUND_COMPLETE event, you work with two Classes: Sound and SoundChannel. The event listener goes on the SoundChannel instance:

var sound:Sound = new Sound("allYouNeedIsLove.mp3");
var soundChannel:SoundChannel = sound.play();
soundChannel.addEventListener(Event.SOUND_COMPLETE, soundIsFinished);

In my project, i rigged up a “Pause” button. When the player clicks “Pause”, i stop the sound and take note of the Sound’s position. When the player clicks “Pause” again, i unpause the game and tell the Sound to start playing where we left off.

But whenever you paused and unpaused the game, the SOUND_COMPLETE Event wouldn’t fire any more.

That’s because whenever you tell a Sound object to play, it returns a new SoundChannel instance. The old SoundChannel instance – the one with the event listener on it – is no longer relevant, so the event doesn’t fire. So to get this to work, when the player unpauses the game, you have to add the SOUND_COMPLETE event listener to the new SoundChannel instance that’s returned when you call Sound.play();

THANKS FOR BAILING ME OUT!

BIG thanks to user WearDark on the Kirupa forums for clearing this up, and for saving me from hours and hours of bug testing trying to figure out what was going on!

http://www.kirupa.com/forum/archive/index.php/t-263824.html

Tutorial: Understanding Classes in AS3 Part 3

In this tutorial, learn how to identify when a chunk of code should be spun off into its own .as Class file.

Trial by Flash

This series of Understanding Classes tutorials chart my progress through unfamiliar Actionscript 3.0 territory. i am a designer-turned-coder, so everything i understand about code was learned in the School of Hard Knocks … most often while a producer breathed down my neck and i had two weeks to program a game using concepts i didn’t grok.

Sgt. Slaughter

Grokking is Half the Battle

i had already learned to avoid “spaghetti code”, a common newbie Flash developer habit where you stick little bits of code on various MovieClip symbol instances and frames throughout your Flash movie. The next step was to round up all of those little bits of spaghetti code and confine it all to the first frame of my Flash movie.

Baby w/ spaghetti

Don’t spaghetti code. Think of the children.

The next leg of the journey into Actionscript 3.0 was to escape the first frame, and to move all of that first-frame code into its own seprate .as Class file. That’s where Understanding Classes began. It seemed like a pointless step – whether the code was in its own frame or in its own Class file seemed like picky Egghead semantics.

The fuzzy picture came more clearly into focus with the next Understanding Classes tutorial, where we learned to write a custom Class to represent symbols in the Flash library. We used the less-than-helpful example of a Dog Class to explain how to pull this off.

Retarded Dog

Thanks for nothing, DOG.

But the time for theory is over. If we’re going to finally learn how to take full advantage of Object Oriented Programming, we need to look at some real-world examples. In this tutorial, we’ll pick through that glob of code in our Main.as file and find places where it makes sense to group chunks of functionality and split them off into their own Class files.

It’s Apparent You’re A Parent

In order to understand when and where to create new Classes, you almost have to think like a parent. All of the methods (things a Class can do) and properties (things a Class is) are your children. As your children grow older, you want them to learn how to take care of themselves. You (hopefully) don’t want to be changing your son’s diapers when he’s 17 years old.

Baby Huey

Worst. Cartoon character. Evar.

So when you look at that mess of code in your Main.as Class, start asking yourself this question: should this kid, this group of properties and methods, be taking care of himself? Is this stuff that me, the Main.as Class, should be doing, or is this something that this kid can go off and do by himself?

Huh?

Here’s a real-world example:

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

	public class Main extends MovieClip
	{
		public function Main()
		{
			var myButton:MovieClip = new MyButton();
			myButton.label_txt.text = "Play";
			myButton.addEventListener(MouseEvent.CLICK, clickMyButton);
			myButton.addEventListener(MouseEvent.MOUSE_OVER, rollOverMyButton);
			myButton.addEventListener(MouseEvent.MOUSE_OUT, rollOutMyButton);
			myButton.mouseChildren = false;
			addChild(myButton);
			myButton.x = 150;
			myButton.y = 89;
			
		}

		public function clickMyButton(e:Event = null):void
		{
			playGame();
		}

		public function rollOverMyButton(e:Event = null):void
		{
			var myButton:MovieClip = MovieClip(e.target);
			myButton.background.gotoAndStop("highlight");
		}

		public function rollOutMyButton(e:Event = null):void
		{
			var myButton:MovieClip = MovieClip(e.target);
			myButton.background.gotoAndStop("unhighlight");
		}

		public function playGame():void
		{
			// Do some stuff here
		}
	}
}

In this piece of code, the Main.as file adds an instance of the MyButton Class to the stage. When the player clicks the button, we fire the playGame method.

There are some things here that the Main.as Class should probably do, and a bunch of things that the LabelButton Class should do for itself. Let me ask you this: why on God’s green Earth should Main.as care about how the MyButton Class implements all of its MouseEvent code? Making the button highlight on rollOver is MyButton’s responsibility, not Main.as’s responsibility.

Rollover

Take care of your own rollover.

Let’s imagine a not-too-distant future. Robots rule the Earth. Gary Coleman is in the White House. And you’re writing a new Actionscript project where you need a MyButton. The way you’ve written it here, can you easily pluck your MyButton Class out of this old project, and plunk it into your new project and expect it to work? No! That’s because you have code that is crucial to the functioning of your MyButton class outside your MyButton Class.

Do the clickMyButton, rollOverMyButton, and rollOutMyButton methods belong to Main, or do they belong to MyButton? Let’s go back to our semi-useless Dog example. Do bark, sniff and peeOnLeg belong to Main, or do they belong to Dog? They belong to Dog. So let’s put them in Dog.

Fat Dog

Stuff everything concerning Dog IN Dog.

Here’s the above script with the MyButton-specific methods removed:

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

	public class Main extends MovieClip
	{
		public function Main()
		{
			var myButton:MovieClip = new MyButton();
			myButton.label_txt.text = "Play";
			addChild(myButton);
			myButton.x = 150;
			myButton.y = 89;
			
		}

	}
}

Wow! We really cleaned up our Main Class, didn’t we?

Here’s what our MyButton Class looks like. We’ve just plucked the methods out of our Main Class and put them where they belong, in MyButton. MyButton changes its own diapers.

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

	public class MyButton extends MovieClip
	{
		public function MyButton()
		{
			addEventListener(MouseEvent.CLICK, clickMyButton);
			addEventListener(MouseEvent.MOUSE_OVER, rollOverMyButton);
			addEventListener(MouseEvent.MOUSE_OUT, rollOutMyButton);
			
		}

		public function clickMyButton(e:Event = null):void
		{
			playGame();
		}

		public function rollOverMyButton(e:Event = null):void
		{
			background.gotoAndStop("highlight");
		}

		public function rollOutMyButton(e:Event = null):void
		{
			background.gotoAndStop("unhighlight");
		}

		public function playGame():void
		{
			// Do some stuff here
		}

	}
}

If you’re keen-eyed, you’ll notice that we were even able to cut down the code when we moved it to the MyButton Class. Instead of saying myButton.addEventListener(MouseEvent.CLICK, clickMyButton);, we can drop the “myButton” part and just say addEventListener(MouseEvent.CLICK, clickMyButton);. That’s essentially the same as saying this.addEventListener(MouseEvent.CLICK, clickMyButton);. The “this” keyword is like saying “me”. We’re inside the MyButton world, so we’re referring to ourselves. While we are writing code inside the MyButton class, we are MyButton.

Starting an Argumemt

Now what about that line in Main.as where we label the button?

myButton.label_txt.text = "Play";

Is labelling the button a responsibility of Main.as, or a responsibility of MyButton.as? The answer is slightly tricky.

MyButton might not always be labelled “Play”. We could (and should) think generically, so that MyButton could be labelled “Play” or “New Game” or “Change Character” or whatever. So Main.as should be responsible for labelling the button, right?

Not exactly. MyButton should still be responsible for labelling itself. But Main.as should be responsible for deciding what that label says. That way, Main could create buttons that say “Play”, “New Game” and “Change Character”,all using the same MyButton Class. The MyButton Class takes care of all the logic of actually displaying that text on itself.

To pull this off, we pass a parameter to our MyButton Class from Main.as.

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

	public class Main extends MovieClip
	{
		public function Main()
		{
			var myButton:MovieClip = new MyButton("Play"); // Check it out!!!
			addChild(myButton);
			myButton.x = 150;
			myButton.y = 89;
			
		}

	}
}

Main.as creates a new MyButton instance (stamp, copy), and passes something called a parameter to the MyButton Class. MyButton grabs that parameter and uses it to label itself.

Note: if you’re fuzzy on the concept of datatypes (String, Number, Int, Boolean, etc), you may already be in over your head. Go read a basic tutorial on datatypes, and come on back.

Here’s the MyButton Class, now modified to grab that parameter from Main.as (or whatever Class instantiates [makes a stamp of, makes a copy of] the MyButton class).

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

	public class MyButton extends MovieClip
	{
		public function MyButton(labelName:String)
		{
			label_txt.text = labelName; // Grab that parameter and label myself!

			addEventListener(MouseEvent.CLICK, clickMyButton);
			addEventListener(MouseEvent.MOUSE_OVER, rollOverMyButton);
			addEventListener(MouseEvent.MOUSE_OUT, rollOutMyButton);
			
		}

		public function clickMyButton(e:Event = null):void
		{
			playGame();
		}

		public function rollOverMyButton(e:Event = null):void
		{
			background.gotoAndStop("highlight");
		}

		public function rollOutMyButton(e:Event = null):void
		{
			background.gotoAndStop("unhighlight");
		}

		public function playGame():void
		{
			// Do some stuff here
		}

	}
}

Beautiful! In this line, we accept a parameter:

public function MyButton(labelName:String)

And in this line, we grab that parameter and use it to label ourselves:

label_txt.text = labelName; // Grab that parameter and label myself!

Jockeying for Position

Finally, we’ll talk about the x/y lines in the Main Class:

myButton.x = 150;
myButton.y = 89;

Is that something that Main should be responsible for, or something that MyButton should be responsible for? x and y are properties of MyButton, so MyButton should handle them, right?

Not so fast! While we could let MyButton position itself, it wouldn’t make sense to. The Class that needs a MyButton should decide where on the screen the button should go. Otherwise, every time we create a new MyButton instance, it’ll appear in the same place on the screen. Not so hot. Main.as should take care of positioning the button instance.

Real Ultimate Power

Et voila! We’re in good shape now. We’ve:

  1. Identified a chunk of code that should change its own diapers
  2. Moved that code to its own .as Class file
  3. Thought generically about how an instance (stamp, copy) of that Class should be treated

Now, check out the glorious wonderland we can experience and enjoy:

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

	public class Main extends MovieClip
	{
		public function Main()
		{
			// Instantiate a new play button:
			var myPlayButton:MovieClip = new MyButton("Play");
			addChild(myPlayButton);
			myPlayButton.x = 150;
			myPlayButton.y = 89;

			// Instantiate a new instructions button:
			var myInstructionsButton:MovieClip = new MyButton("Instructions");
			addChild(myInstructionsButton);
			myInstructionsButton.x = 210;
			myInstructionsButton.y = 89;

			// Instantiate a new credits button:
			var myCreditsButton:MovieClip = new MyButton("Credits");
			addChild(myCreditsButton);
			myCreditsButton.x = 340;
			myCreditsButton.y = 89;
			
		}

	}
}

Wowee! THREE new button instances in half the code it took to have ONE button when we first started out.

We’re almost out of the woods. But there’s one nagging thing remaining. Notice that we have a method in the MyButton Class that looks like this:

public function clickMyButton(e:Event = null):void
{
	playGame();
}

Should MyButton decide what happens when it gets clicked? We saw that the Main.as Class can quickly create three instances of MyButton – a Play button, an Instructions button, and a Credits button. These three buttons are all going to do different things when the player clicks them. So the generic MyButton Class cannot possibly define its own click behaviour. Main.as is going to have to decide.

Let’s yank that click code right out of the MyButton Class:

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

	public class MyButton extends MovieClip
	{
		public function MyButton(labelName:String)
		{
			label_txt.text = labelName; // Grab that parameter and label myself!

			// this is where the MouseEvent.CLICK listener used to be

			addEventListener(MouseEvent.MOUSE_OVER, rollOverMyButton);
			addEventListener(MouseEvent.MOUSE_OUT, rollOutMyButton);
			
		}


		public function rollOverMyButton(e:Event = null):void
		{
			background.gotoAndStop("highlight");
		}

		public function rollOutMyButton(e:Event = null):void
		{
			background.gotoAndStop("unhighlight");
		}

	}
}

And instead, we’ll write the listener for each button’s MouseEvent.CLICK in the Main.as Class:

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

	public class Main extends MovieClip
	{
		public function Main()
		{
			// Instantiate a new play button:
			var myPlayButton:MovieClip = new MyButton("Play");
			myPlayButton.addEventListener(MouseEvent.CLICK, clickBtnPlay); // new line!
			addChild(myPlayButton);
			myPlayButton.x = 150;
			myPlayButton.y = 89;

			// Instantiate a new instructions button:
			var myInstructionsButton:MovieClip = new MyButton("Instructions");
			myInstructionsButton.addEventListener(MouseEvent.CLICK, clickBtnInstructions); // new line!
			addChild(myInstructionsButton);
			myInstructionsButton.x = 210;
			myInstructionsButton.y = 89;

			// Instantiate a new credits button:
			var myCreditsButton:MovieClip = new MyButton("Credits");
			myCreditsButton.addEventListener(MouseEvent.CLICK, clickBtnCredits); // new line!
			addChild(myCreditsButton);
			myCreditsButton.x = 340;
			myCreditsButton.y = 89;
			
		}

		public function clickBtnPlay(e:Event = null):void
		{
			// Play the game
		}

		public function clickBtnInstructions(e:Event = null):void
		{
			// Show the instructions
		}

		public function clickBtnCredits(e:Event = null):void
		{
			// Show the credits
		}

	}
}

And there you have it. The MyButton Class takes care of its own diapers. It labels itself based on a parameter that’s passed to it. It handles its own rollOver and rollOut events. Main.as takes care of creating instances (stamps, copies) of the MyButton Class. Main.as decides:

  • What the button label will say
  • How the button will be positioned on the screen
  • What the button does when clicked

The First of Many

That’s a real-world example of where and when it makes sense to collect your code in a separate Actionscript Class file. Of course, this is just one example in an endless sea of possiblilities. The general rule is that if the code should be changing its own diapers, it should be in its own Class file. And if the code can be written generally so that it can be re-used, you’re ahead of the game.

The mystery that springs up from all of this is the OOP rule of Encapsulation, which states that you should write your Classes so that they’re self-contained and self-reliant. Not only do they change their own diapers, but they rent their own apartment and cook meals for themselves, with no reliance on outside Classes whatsoever to live.

There are advantages and disadvantages to Encapsulation, which we can look at in our next Understanding Classes tutorial. The biggest disadvantage is that to create a truly encapsulated Class, you have to write an ASSLOAD of repetetive Actionscript 3 code. i’ll show you a cheat that’ll break the encapsulation rule, but will save you HOURS of coding. The Eggheads will have my head for it, so let’s just keep it between you and me.

For more tips, tricks and tutorials on Flash and Actionscript, check out our Flash and Actionscript 911 feature.

Saved Game (a Kindisoft secureSWF Review)

Full Disclosure: This is a paid review. We are receiving a free license of Kindisoft secureSWF in exchange for evaluating the product and posting our opinion. This has not necessarily effected a positive or negative review; while a post can be bought, our favourable opinion comes at a higher price. (That price, incidentally, is one large basket of Peek Frean’s chocolate Bourbon Cream cookies, a variety of points cards for leading video game consoles, a 1-year subscription to Games Magazine, and a commercial-grade Sno Kone machine.)

Bourbon Cream Cookies

i would give WISDOM TOOTH EXTRACTION a positive review for a basket of these babies

What follows is a review by Jeff Gold (ue_jeff), our indomitable Game Developer and Keeper of All AS3 Knowledge.

From the Mouths of Jeffs

Today I set out to evaluate Kindisoft secureSWF, a product designed to help Flash / Flex developers secure and obscure their flash content from prying eyes. Thanks to several products on the market today (I am going to use SoThink SWF Decompiler as my point of reference here) it is possible, and quite easy, to open up Flash content found online to view and re-use all of the file’s source code and art assets. There are many reasons why developers would not want their files being decompiled this way. Theft of ActionScript code, theft of art assets, and hacking of controlled systems are just three.

Log in to the MochiMedia community forums and read this post about how one developer’s game was completely ripped off by someone with a swf opener:

psyon
Sep 07, 2009

On of my puzzle games was hacked. The person replaced my site logos, but apparently left my mochibot code in place, so I can see where all the hacked copies are. Anyone familiar with the site OyunKolu.com ?

SecureSwf was recommended to us by a number of our Twitter friends, including Chris Hughes from Flash Game License/GamerSafe. We had been evaluating other encryption software (most notably Amayeta SWF Encrypt 6.0) and were not entirely impressed with the Actionscript 3 code obfuscation. With Amayeta’s product, I found that using anything but the most minimal settings made my swf report many errors.

Old School Robot

ERROR! ERROR! DOES NOT COMPILE!

That New Software Smell

Upon opening SecureSWF I immediately noticed many options compared to the other products we had tried.

secureSWF standard setup

A simple charting app that we used in Interrupting Cow Trivia

Our first victim: a pie chart swf that we use in Interrupting Cow Trivia

Being momentarily overwhelmed by all the panels in front of me I decided to just try out the default configuration. On the first simple swf I tried to encrypt, the default configuration worked quite well causing no errors while running the swf.

secureSWF default settings

secureSWF’s default settings

Immediately after encrypting my first swf with Swf Encrypt, I busted out my swf decompiler to see the results. Decompiling the swf was still possible ( I think this will be the case with any swf encryption ) , but inspecting the extracted code I could see a fair deal of obfuscation had occurred. (Obfuscation Translation: Code is EFFED-UP. – Ryan) With the default settings, Class names, function names, and class variables are obscured to things such as “_-V” or “_-02″, making the code very hard – but not impossible – to follow. I did notice immediately that variables scoped in functions were not obscured , but were left as var _loc_1 , var _loc_2 etc. as the compiler defines them (which I suppose is already obscure).

before secureSWF

Before secureSWF …

before secureSWF

… After secureSWF.

Giving It Some Welly

This one goes to 11

My next step was to crank up the security settings on the same simple swf. This time around I went to protection options and checked “Statement-level Randomization”, Maxed out “Control Flow Obfuscation” and “Dynamic Code Wrapping”, and checked “Break function Calls”. Honestly I am not 100% sure what all these things are doing, but I just went for overkill settings.

secureSWF cranked settings

Overkill settings.

The swf still managed to run without any errors, and like last time I was still able to decompile the swf. Taking a look at the code again I immediately noticed quite a bit more obfuscation at the function level, and the code seemed more verbose and harder to follow.

before secureSWF

Again, the same code before secureSWF …

secureSWF max settings

.. and after, with settings cranked to the max.

Enter the Cow

So after my successful runs on a simple application, I tried to run a complex application through the process (Interrupting Cow Trivia, our real-time multiplayer trivia game) once again with default settings. At first the swf seemed to work with no errors, but after doing some stress testing I did notice few issues. After about 20 minutes of tinkering with the many settings available I figured out the culprit: “Control Flow Obfuscation”. Turning this one option off and then cranking all the other options managed to produce a 100% functional swf for me, and after decompiling I could not discern much difference from with the option on.

Spot the difference

Spot the difference.

secureSWF has some other interesting features that I had not seen in other products (but, to be fair, I haven’t tried every competing product). These features include “Encrypted domain locking” and “Literal String Encryption”. I am not sure how the encrypted domain locking works , but it is a nice option and saves you from having to setup your own site locking in ActionScript each time. (Site-locking prevents your swf from being played on any domain other than the one[s] you specify.)

Literal String Encryption is another nice feature as it allows you to encrypt potentially sensitive text in your code. By default, strings will not be encrypted and will be perfectly readable when the code is decompiled. I am sure this process could be reverse engineered by digging through the code, but either way it just adds another barrier to the hacker to keep him from messing with your work.

Overall, Kindisoft secureSWF seems to be a solid product with lots of customizable features – far more than its competitors – that we plan to take advantage of for current and future projects.

End Jeff Transmission

Ryan: Of course, swf encryption is just one side of the story. If you have a game that posts information to your server to store high score data, to save games, etc, it’s important to know that all that stuff is wide open. Just grab Fiddler, a “web debugging proxy”, and run it while you play any game that makes server calls. With an unprotected game, you’ll be able to sniff out the exact asp or php page where scores are being posted, and you can use that info to trick the server into posting a high score for you. You can also use an app called Cheat Engine to wreak serious havoc with an online game, Flash or otherwise. Here’s how:



You may be wondering why, for the love of all that is Holy, we would be linking to movies and products about how to hack Flash games in a review of encryption software. It’s to illustrate the point that no protection solution is 100% effective (which is also why i have two children running around my house). Another saying i really like is “locks keep the honest people out”.

You’ll never make your game immune to hacking, but you can throw so many locks and contrivances in the way that it might take some serious skill to unlock them … and it follows that anyone with enough haxxor skillz to get through all those locks has something better to do with his considerable talents than to post a high score to your free-to-play Escape the Room game.

Win a Copy of secureSWF

Kindisoft is offering a 25% discount on secureSWF through various Flash game development sites, including FlashGameLicense.

For more articles about Flash and Actionscript, check out our Flash and Actionscript 911 feature.

Moo.


[kml_flashembed publishmethod="dynamic" fversion="8.0.0" movie="http://www.untoldentertainment.com/games/interruptingCowTrivia/img/promo/blog_promo_bar.swf" width="545" height="185" targetclass="flashmovie" wmode="transparent"]

Get Adobe Flash player

[/kml_flashembed]

Tutorial: Understanding Classes in AS3 Part 2

In our first thrilling look at Understanding Classes in Actionscript 3.0, we talked about how Classes are structured, and how you can make that leap from stashing all your code in the first frame of your Flash movie like an IT chipmunk, to moving your code to its own Class.

I promised that in Part 2, we’d learn how to identify chunks of code that should be moved into their own Classes. But before we do that, it’s important to talk about what a Class is. And if you haven’t learned how to extend a MovieClip symbol in your library to write a Class around it, this tutorial is for you!

Take THAT, eggheads

Disclaimer Dear Eggheads: This tutorial is between me, a designer-turned-coder, and readers who want to learn more about Actionscript programming who likely are not Computer Science graduates. The terminology i use may not be 100% accurate, and some of the things i say may inflame your nerd rage and your unwavering demand for technical accuracy. But this article is not for you. Stop reading now. Go write some slash fiction about Captain Kirk totally doing it with the dog from Battlestar Galactica, and leave us alone to learn.

OOP: There It Is

A Class is an element of OOP – Object Oriented Programming. OOP is a flavour of coding where different objects – or things – interact with each other to solve a problem. If you’re a game programmer, the problem can be described as “How do i make a fun, functional zombie game?” The word “object” is synonymous with “Class”. You could say that Actionscript 3.0 is a Class Oriented Programming language, but the eggheads would stab you in the face.

She-Nerd

She-Nerd SMASH!!

So a Class is a thing – a chunk, a morsel, a module of code. By writing your Classes the “right” way, you’ll find you can re-use Classes from project to project. By writing them the “wrong” way, you’ll still probably wind up with a project that has nice, well-organized code that makes sense if you re-visit it a year later.

The three principles or rules to follow if you want to maximize the advantages of OOP are encapsulation, inheritance and polymorphism. We’ll be taking a brief, gentle look at inheritance in this tutorial, because i think it’s the easiest to understand when you’re starting out.

Inbred Twins

Herbert n’ Zed inherit their genes from their paw n’ their sis

Classes contain methods and properties. (Another word for “method” is “function” or “behaviour”. Another word for “property” is “field”.) A method is something a Class can do. A property is something a Class is.
Let’s explain this somewhat better by using a crappy example that a lot of OOP tutorials use. You have a Class called “Dog”. Methods of Dog – things that Dog can do – include:

  • bark
  • sniff
  • humpLeg

Properties of Dog – things that dog is – include:

  • color
  • breed
  • favouriteTreat

Another way to think of it is that methods are verbs, and properties are adjectives.

Ugly Dog

The OOP Dog example rears its ugly head

Let’s Get Real

The Dog example is almost entirely useless to us as programmers. In all my years of experience, i have never written a Dog Class. But i HAVE written my fair share of music and movie players in Flash. Let’s look at the methods and properties of a media player.

Methods of our MediaPlayer Class – things that a media player can do – include:

  • play
  • pause
  • stop
  • scrub
  • changeVolume
  • loadMedia

Properties of our MediaPlayer Class – things that a media player is, or things that describe its state – include:

  • isPaused
  • songDuration (or movieDuration)
  • isFullScreen
  • volume

Note that the method “changeVolume” probably changes the property “volume”.

Snowths

We’re gonna need a method called “turnVolumeWayWayUp”

You’re Already an Expert

The good news is that as a Flash developer, you’ve been using Classes this whole time, though you may not have known it. A MovieClip is a Class. It has methods and properties. Let’s look at some of the methods of a MovieClip – things a MovieClip can do:

  • gotoAndPlay
  • stop
  • hitTestPoint (determine whether a point is colliding with me)

And some properties of a MovieClip – things a MovieClip is (or things that describe its state):

  • x and y
  • alpha
  • rotation

Eggheads: Are you still reading this? i told you to take a hike. Don’t jump down my throat. i know that a few of these methods and properties actually belong to Classes that MovieClip inherits from, but we’re just learning, alright? Leave us alone. Go out and LARP or something.

LARP

No Pain, No Awesome

Just as you can make the leap from stowing all your code in the first frame of your movie to putting it in an .as Class file, you can (and should) make the leap from having all of your MovieClip instances “physically” present on your stage, to keeping them in the library and drawing them to the stage using code. There are many advantages to using a code-only approach which probably won’t become clear to you until you go through the excrutiating growing pains of “WHY THE HELL AM I DOING IT THIS WAY??” like i did.

Growing Pains

Growing Pains: excrutiating

So create a MovieClip in your library. NOTE: If you don’t know how to do this, you may already be in over your head. Go check out a beginner Flash tutorial and come on back.

In order for you to make the MovieClip available to you through code, you need to give it a linkage name. Here’s how:

  1. Open your Library (CTRL+L)
  2. Right-click the MovieClip symbol
  3. In Flash CS3, choose “Linkage”. In Flash CS4, choose “Propeties”.
  4. Check the box that says “Export for ActionScript”
  5. In the “Class:” field, type a logical name for your MovieClip. It’s best practice to start this name with a capital letter. Don’t use any spaces – capitalize each new word SoThatItLooksLikeThis. (This is called “Pascal case”)
  6. Click “OK”
  7. If you are a Mac user, and you’re saying “What’s a CTRL?? What’s a right mouse button?? i’m freaking OUT, man!”, go buy a PC ;)

Linkage CS3

Setting linkage for a library item in Flash CS3 …

Linkage CS4

… and in Flash CS4.

Linkage Name

Choosing a linkage name

Did you notice, before you hit OK, that there was a field labelled “Base Class:” that said “flash.display.MovieClip”? If this is your first time creating a library linkage, or if it’s old hat and you’ve never noticed this field, prepare to blow your own mind: you’ve just used the first principle of OOP – inheritance.

My Mind Done Blow’d Up

Here’s what’s going on behind the scenes. “MovieClip” is a built-in Class that the creators of Actionscript wrote. When you give your library item a linkage name, you are actually subclassing, or inheriting, from the MovieClip Class. That means that your new Class “Dog” or “MediaPlayer” or “EnemySpaceship” can now do all the stuff that a MovieClip can do. It can gotoAndPlay, it can stop, it can hitTestPoint, etc. It also inherits all of MovieClip’s properties – x and y, alpha, rotation, etc. – things that a MovieClip is, things that describe its state.

So now we’re getting to the point. When you create a library linkage like this, Flash is automagically creating a new Class (“Dog”, “MediaPlayer”, whatever). You don’t have to write it. But you CAN write it, if you want to. And since that’s what this tutorial is all about, then oh yes – we want to.

Oh Yes – Let’s

Start a new .as Class file. You can do it in the Flash IDE, you can write it with Notepad or Notepad ++ or any other text editor. i highly recommend Flash Develop. Remember our first Understanding Classes tutorial? Here’s the structure of a Class:

AS3 Class Structure

i chose these colours from Arsenio Hall’s wardrobe

So here’s what our empty Class code should look like:

package
{
	import flash.display.MovieClip; // Import statement(s)

	public class Dog extends MovieClip
	{
		// Class definition

		private var isBarking:Boolean; // Instance variable(s)

		public function Dog()
		{
			// Constructor function
			trace("i am a dog");
		}

		// Other functions
		private function bark():void
		{
			isBarking = true;
		}

		private function stopBarking():void
		{
			isBarking = false;
		}
	}

}

Let’s take note of a few important things.

  1. i’m calling my Class “Dog”. That’s because the linkage name in used in the Flash library was “Dog”. Note: not “dog” or “DogClip” or anything. D-o-g. Same capitalization, exact same name.
  2. And note that the linkage name can be completely different from the library symbol name. My library symbol could be called “This is a thing what i created in teh Flashs”. Doesn’t matter. Actionscript can’t “see” the library item name. It can only “see” the linkage name.
  3. Finally, remember that the Class file name has to be the same as the Class name. If our Class is called Dog, we save the file as Dog.as. Pull any other shenanigans, and you’ll get errors.

Silly dog

i SAID “no shenanigans”, DOG

i mentioned mysteriously in the last tutorial that the word “extends” is an inheritance word. When you create a linkage name in the library, Flash automagically writes a Class for you, and automagically extends (inherits from) MovieClip. Now that we’re writing the Class ourselves, nothing is automagic. We have to explicitly say that Dog (or whatever) extends (inherits from) the MovieClip Class. When this is all done correctly, Flash understands that there is a connection between the linked library Class “Dog”, and the “Dog.as” Class we just wrote.

You may or may not know the code for dynamically placing a linked library item on the stage. Here it is, using Dog as the example:

var dog:MovieClip = new Dog();  // or var dog:Dog = new Dog();
addChild(dog);

“BUT WAIT!”, you say. “I THOUGHT DOG HAD TO START WITH A CAPITAL LETTER??” Okay, first of all, stop yelling. Lower-case “dog” is the name of the variable that contains an instance (a stamp, a copy) of our master Dog Class. We could use “dog1″, “dog2″, or even “thisIsACopyOfDog”.

When you addChild(dog), you add your instance (stamp, copy) of the Dog Class to the list of things for Flash to draw to the stage (the viewable area that the player sees).

To confirm that your custom library Class is working, test your movie. You should see the trace action “i am a dog” in the Output window. (Press F2 to see the Output window – the trace action won’t appear on the stage)

What’s the Point?

You may be wondering why we went through all of this agony. The easy way is just to draw a dog and make it a MovieClip, and then leave it on the stage. There are many, many advantages to what we’ve just done. Let me list a few:

  • You can now add as many Dogs to the stage as you like dynamically. Until now, you had to add them by hand. If you needed another dog, you (the creator) had to drag one out of the library. Now you can create an “Add Dog” button. When the player presses it at run-time, your code dynamically places dogs on the stage. Now the code is doing the work, not you.
  • We’re edging closer to the next OOP principle, encapsulation. Within our Dog class, we can store methods (things that a Dog does) and properties (things that a Dog is). Every time we initialize (make a stamp or copy of) Dog, Dog can run a bunch of Dog-specific setup routines: initializeSenseOfSmell, testBarkTone, prepareToChewShoes. If you do it “right”, you’ve created a self-reliant, self-contained Class. Now every time you have a project that needs a Dog (or a MediaPlayer, an ImageGallery, a CountdownClock), you can just copy that .as Class file to a new project. If you’ve done everything “right”, it’ll just work.
  • The more you start abstracting your thinking, the more you’ll be able to write generic Classes that do a number of different jobs. You might not have another project that needs a Dog, but your generic Animal Class would still do the trick.
  • There’s a problem that Actionscript 3 introduced where you can’t always access certain pieces of MovieClips until they’re drawn to the screen. Writing a custom Class for your library elements can overcome this problem.

What’s Next?

Moving your frame code to an .as Class file was the first step. Learning how to write custom Classes for your linked library items is the next step, since it builds on (hopefully) familiar MovieClip territory and your existing knowledge. In the next tutorial, we’ll take a look at that big wad of code in your Main.as file and try to figure out which methods and properties can be logically grouped and moved into their own Classes.

For more tips, tricks and tutorials, check out our Flash and Actionscript 911 feature.

AS3 Pitfalls – stop(); Action Ignored on Nested Movieclip

PROBLEM:

You’ve got a movieclip with a stop action on the first frame. When it appears on-screen, it inexplicably starts playing on frame 2, ignoring frame 1 and your stop action entirely.

The movieclip in question is probably embedded into a parent clip that you’ve dynamically added to the stage from the library using the “new” keyword and “addChild” method.

SOLUTION:

You’re not going to like this. This bug is one of many we’re discovering as we finally make the painful, money-losing transition from AS2 to AS3 for all our future projects. You have two options:

  1. Put an extra frame at the beginning of the movieclip, with the stop(); action on frame 2. This solution completely stinks, but welcome to our brave new world where Adobe ignores the needs of designers and caters only to people who code absolutely everything and don’t use the timeline.
  2. In my case, i was able to stop the clip on frame 1 by making an explicit call from the method that attached the parent clip, like so:
var parentClip:MovieClip = new ParentClip();
addChild(parentClip);
parentClip.childClip.stop();
// where childClip is the one that's giving us problems

Further Reading:

Here are some of the places i hit on my merry way to finding the so-called answer to this problem:

Flashkit: AS3 stop(); code not working??

actionscript.org: AS# stop(); doesn’t work