Pre-Object Oriented Programming (OOP) for Actionscript, part 5

July 22nd, 2007 . by polyGeek

Errors, Errors, everywhere but nary an idea what’s wrong

That’s the feeling we all get when we’re trying new things in Actionscript. Our FLA won’t publish because there’s some error and you’re thinking, “What the Frak does that mean?”

So here are a handful of common error messages that you get when using classes and what they mean.

The class or interface ‘<SomeClassName>’ could not be loaded.

You either have the path/namespace or the class name wrong. It’s probably a typo somewhere. As an example, if you are using the Holtzman class and you wrote this code:

var h:Holtzman = new Holtzman(....

You would get the above error because you either forgot to use the full namespace or to import the class. You could fix that by either doing this:

var h:com.polygeek.utils.Holtzman = new com.polygeek.utils.Holtzman(....

or this

import com.polygeek.utils.Holtzman;
var h:Holtzman = new Holtzman(....

The class being compiled, ‘<SomeClassName>’, does not match the class that was imported, ‘com.polygeek.utils.SomeClassName’.

This is easy. You have a class that you created in a specific namespace but you forgot to tell the class what namespace it’s in. Here’s an example: you have a class <SomeClass> in the com.polygeek.utils folder and the class declaration looks like this:

class SomeClass {

It should b:

class com.polygeek.utils.SomeClass {

The property being referenced does not have the static attribute.

This one is a tough one to describe unless you understand OOP in the first place. By example suppose you wrote the following code:

MovieClip._alpha = 50;

You know that doesn’t make any since because _alpha is a property of an individual MovieClip. You can’t set the _alpha of all MovieClips with code like that above. You would have to go to each instance of all MovieClips and change their _alpha individually.

A constructor may not specify a return type.

The constructor cannot have a return type, not even :Void. So your constructor looks like this:

public function SomeClassName() {...

Not like this:

public function SomeClassName():Void {...

As I think of more common errors I’ll add them to this page. Feel free to suggest your own in the comments and I’ll add them here.

Happy debugging.


Pre-Object Oriented Programming (OOP) for Actionscript, part 4

July 22nd, 2007 . by polyGeek

A common discussion I’ve had with other developers about learning Object Oriented Programming in Actionscript is: for people new to OOP which is better to learn: Actionscript 2.0 or Actionscript 3.0.

Here are my thoughts on the subject:

If you already know a little bit of Actionscript 2.0 and you want to expand your skill set then go ahead and learn OOP for AS2. You can then pick up AS3 when the need arises. I believe that there will be designers and developers delivering Flash projects using AS2 for years to come.

If you are a designer/developer working on small projects like creating video interfaces, or brochure type sites that are animation intensive then I suggest learning AS2.

On the other hand if you plan to work on projects like building Rich Internet Applications that can scale to include all sorts of components and using dynamic data from web services or Flash Remoting, etc. then you should think about jumping straight into AS3.

The gray area comes if you expect to be building widget type Flash projects. In that case you could go either way. You might be more productive right off the bat with AS2 and OOP but down the road you will probably want to start picking up AS3 and OOP.

The advantage to OOP in AS3 is that it is much more rigorous in how it treats code. Things that you can get away with in A2 will cause errors in AS3. And that’s a good thing because it helps you debug your code faster. The downside is that some things that are very simple to do in AS2 become a bit more involved in AS3. But things that are very code intensive in AS2 become trivial in AS3.

I hope I have helped to confuse you beyond repair. Now get to work. :-)

In part 5 of this series I’ll cover a few of the common error messages you’ll get while using classes and what they mean.


Pre-Object Oriented Programming (OOP) for Actionscript, part 3

July 22nd, 2007 . by polyGeek

Have you ever been working on a project where you’re writing some Actionscript and you think to yourself, “I know I’ve done this before. Where is that code. It’s in an FLA around here somewhere . . . ”

That problem is one of the things that object oriented programming is good at solving. It helps you externalize your code and organize it so that you can reuse those common bits over and over.

Thus far the classes that we have created in parts 1 and 2 have been written in .as files sitting in the same folder as your FLA. Sometimes that’s okay because those classes might be pretty specific for the project you are working on. But what if you have written some methods that could be really useful for other projects. You don’t want to have to copy that .as file to other folders just to use it.

The Flash authoring tool gives you a way of putting your commonly used class files in one location that can be accessible to all of your FLAs. No matter where they are on your computer.

Here’s what you need to do:

  1. Open the Flash authoring tool
  2. From the menu bar select Edit -> Preferences
  3. Select Actionscript from the Category nav on the left
  4. Click on the Actionscript 2.0 Settings button
  5. Click the “+” button to add another Classpath [see image below]
  6. Now click the target button - it’s the one in the center. This will allow you to browse to the folder where you’re going to put your classes.
    • Note: this is a very important folder. You don’t want to put it somewhere where it could accidentally be moved or deleted.
    • However, you want to be able to get to it easily. Plus, you might need to zip the files up in this folder to send to other people.
    • Remember, you cannot publish your FLA if you don’t have your class files. So if you’re working on a project with someone else you will need to share the files in this folder with them.
  7. All done? Click Ok

You can see that my Classpath is : C:\Documents and settings\polyGeek\Desktop\FlashSpace\GlobalClasses

Actionscript Settings Global paths

Now that we can write reusable code what should we do first? One of the things that I have to do in just about every project is load external images and SWFs. If you’ve done this yourself you realize it’s a bit of a pain. You have to create listeners, and functions, and all sorts of things. I think it would be great if we had a utility that could handle all this for us.

Here’s the code below for a utility that I have written to make it easy to load external assets into your SWF. A detailed explanation of how to use it follows.

First off take a look at line 14.

class com.polygeek.utils.Holtzman {

That’s a bit different from what you’re used to in creating classes thus far. What’s up with that?

Suppose you wrote a class, we’ll call it, FlashUtils. You put it in your global classpath and use it on a number of your projects. Everything works just fine until you download someone’s class that does some really cool stuff but its name is also FlashUtils. Now what?

Now you know that you can’t change the name of your class because then you would have to go back to every project that uses it and change the name there as well. And you don’t want to mess with someone else’s code.

The solution is that everyone puts there classes in a unique namespace. One thing you can be sure of that is unique is an internet domain name. So my global classes are in com.polygeek. Everything that comes after that are for my own organizational purposes. The Holtzman class is on the folder utils because it’s a utility.

Another thing to note is that classes are given names that reflect their purpose. You might be wondering what Holtzman is. If you hadn’t guessed by now I’m a geek and being a geek I like to chose geeky names for things. Is it consistent with best practices? Maybe not but that’s what you get for learning object oriented programming from a philosophy major. :-)

Back to using this Holtzman class. Go to your global class path that you set up from above and create a sub folder named com. And inside of that create a folder named polygeek. And once more for the utils. Notice that all the folder names are lower case which is consistent with best practices - sometimes I do things right.

Now create an .as file named Holtzman and paste the code from above into it.

Here’s how you use the class.

Create an FLA and paste the code below into it.

Publish and you should see two images - the polyGeek logo - one rotated +15 degrees and the other -15 degrees. And one of them has smoothing turned on. You can see that if you resize or rotate an image you probably want to use smoothing.

Here’s a quick synopsis of what’s happening:

  1. When you instantiate the Holtzman class you pass, at a minimum, the MovieClip to load the image into and the path to the image/swf.
  2. If you would like to do something like resize the image you have to wait until it has completed loading. That’s what the onImageLoaded function is for. You can name that function anything you like.
  3. Any parameters passed to the Holtzman class, after the smoothing: true/false, will be attached to the external asset you loaded so that you can access them in your callback function. That’s useful if, for instance, you are loading a series of images and you want to rotate each one a different amount. You can make up a variable name, like rotateThisMuch, and then the value you want to rotate to.
  4. The callback function you specify receives on Object of type MovieClip. That MovieClip will have a property of rotateThisMuch with the value you specified in the next parameter. This is an added feature that you probably won’t need very often but when you do it comes in very handy.

The great thing about all this is that you don’t have to understand any of the code inside the Holtzman class to use it. All you need to know is how to instantiate it - lines 16-20 and 22-26 - and what parameters to pass to it.

Word of warning: when you create a class that gets used across projects you have to resist the urge to modify it. For example, if you changed the order in which the class accepts parameters then all the places where you used it before would be broken.

Also notice that when you accessed the Holtzman class you did so through the constructor. Meaning your instantiated the class to create a new object. In this case it’s rather trivial but that is a new object and so you’ve now done object oriented programming.

Congratulations.

I would now suggest that when you feel comfortable with what you’ve learned to this point that you read Colin Moock’s book: Essential Actionscript 2.0. It’s pretty much the definitive source of learning OOP in Actionscript.

In part 4 I’ll give you my two-cents on weather or not to start learning Actionscript 2.0 or Actionscript 3.0 first.


Pre-Object Oriented Programming (OOP) for Actionscript, part 2

July 21st, 2007 . by polyGeek

In the first part of my Pre-OOP lessons you learned how to use classes as a substitute for _root or Global variables. It is an approach that is far from best practices but it does get you initiated to the syntax of classes and Actionscript.

In part 2 we’ll build on the basics that you learned and start applying some of those best practices.

Now you know how to create a class and add some public static properties and methods to it. You might be wondering what’s up with the public part. It’s really pretty simple. Anything that is public can be seen from outside of the class, like from your published SWF. But if you changed those publics to privates you wouldn’t be able to access those properties from any code unless it is inside the class.The next step in learning object oriented syntax is to make all of your properties (variables) private.

You might be thinking, “Doesn’t that defeat the purpose of what I learned in part 1? Not at all, you’ll still be able to access your properties (variables). You’ll just do it in a different way.

This is what you did before:

This is what you’ll do now:

The only difference is that all of the properties are now private and there are 4 new methods - 2 for each property - that we use to interact with those properties. Those are the getters and setters.

If you look at this code it really looks like a lot of extra work just to get the same thing done. But there is a method to this madness.

Here’s the reason for that. Suppose you have a property, well call it hourOfDay, which is a number that represents the hour of the day. You know that it’s a number between 0-23 in all cases. The old approach to programming is to simply update the value hourOfDay directly. The problem with that is that if you make an error you might assign a number that is greater than 23. Or it could be a decimal value when you always intend for it to be an integer.

There are any number of mistakes that could happen in your code that would allow you to assign a value that is out of range.

To fix that you make hourOfDay private so that you cannot access it directly. Then you create a method (function) to update the variable - set - and another one that retrieves the value - get. I’m going to make a new class for this and call it TimeTracker. (This is a file named TimeTracker.as that sits right next to my FLA file.

It’s just a convention to make the method names start with get and set. I could have named those methods anything I wished but it makes it more readable to prepend get/set.

Note: there is another syntax that is commonly used for getters and setters that would look like this:

public static function get hourOfDay():Number { ...

I prefer to use the former but they both do the same thing.

Now back in my FLA I’ll write this code:

What’s great about this approach is that you will get a message in your Output window any time you make an error trying to update hourOfDay incorrectly. Which makes it much easier to fix your code when things go wrong.

If you step back and think about it here’s what you’ve learned thus far:

  1. You can create a class where you can store variables that you want to be able to easily access from any line of code in your FLA.
  2. You have created properties that cannot be directly accessed.
  3. You have created methods through which your can get and set the value of your properties.

Just that little bit right there is a huge step in writing code that is easier to debug and maintain. Trust me: it will pay huge dividends. While it may be a pain to write all those getters and setters they do go pretty quick. Once you get used to it you’ll just fly through creating them.

One added bonus is that all those getters and setters look like you have written a lot of code. So when you’re showing your manager something in your code they’ll see long scrolling lines of code and think you’ve put in a lot more than you actually have. Which is also another argument for commenting your code but that’s another story. :-)

In part 3 I’ll show you how to use what you’ve learned so far to make your code more reusable.


AIR Bus Tour: Seattle Experience

July 11th, 2007 . by polyGeek

I just got back from the Elysian Fields where Adobe kicked off it’s onAIR Bus tour for 2007. The sessions that I saw were all pretty good. There was a bit of disorganization and the typical tech issues. All in all they put on a good show.

If the onAIR tour is coming anywhere near you then I highly suggest attending. Even if the sessions are of no interest to you it’s always great to meet developers of the same ilk. Plus you’ll have the opportunity to go right to the source and have conversations with Adobe employees who can make a difference in what the products we use.

I listened in while a developer friend of mine from SmileBox got to ask very pointed questions about the AIR runtime. They would love to use AIR but they require functionality that isn’t going to be supported, at least for version 1.0. His conversation really helps Adobe see what users need and it helps him in making long term plans for their business.

If you think AIR might be something you could use then by all means show up, get someone like Ted Patrick, Mike Chambers, Kevin Hoyt, Daniel Dura, Ryan Stewart, etc, in a corner and ask all the questions you need. They won’t beat around the bus, I mean bush. :-) They’ll answer everything they can.

Speaking of answering questions

Kevin Lynch gave the keynote and one of the questions at the end was, “When is Apple going to support AIR.” His answer was, “You’ll have to ask Apple that question.”

Now this is just me reading into it but the tone that he used didn’t sound like someone who is frustrated with Apple. It was more like the tone someone uses when they know the answer. They want to tell you the answer. But they can’t disclose, yet. It sounded to me like AIR was on the table and it was just a matter of time.

We’ll just have to wait and see. I might even get one if I can write my own AIR apps to put on it.

By the way, I just want to point out that Apple releases the iPhone without support for Flash content and it causes the Earth to wobble a on it’s axis. But the Zune doesn’t support Flash content either, not even FLVs, and no one even notices. I’m not sure but I think that means something.

I got to meet John Dowdel. He saw my name tag and yelled, “polyGeek” and then gave me a high five. That was a real treat. We had lunch together with a few others and had a great conversation. He’s just like his blog: a guy who listens to the conversation around him and then has either a trenchant comment or insightful question.

For me the highlight of the day was the ignight session. Not because I spoke - about video.Maru - but because there were a number of other presentations that really got my attention:

Andre Charland has a really cool product RobotReplay.com. You sign up for an account, drop a line of Javascript in your page, and then you can watch how users move their mouse around on your page. It’s if you want to do usability testing on your actual users as they are using your website.  I’m going to try it out and then write more about it.

I didn’t get to talk to Brian Dorsey after his presentation but maybe we’ll have lunch sometime. His website is Noonhat.com. The idea is to match people up for lunch so that they can have great conversations. He is just in the beginning stages and it only works in Seattle, for now.

Buzz Bruggeman demoed his software ActiveWords. A very intriguing idea. I’m going to test it and write more about it later.

If you can get to one of the onAIR events then I highly recommend you do so. It’s an invaluable experience.


Practical jokes to play on Flash designers (part 2) - randomize TextFields

July 6th, 2007 . by polyGeek

In version 1 of the practical jokes to play on Flash designers I showed how to write a recursive function that bumps all the MovieClips on the stage at authoring time around a few pixels this way or that. Version 2 of this idea is to replace all the dynamic text in an FLA at authoring time with random characters.

Before RND scramble After RND scramble
Before scramble-ization

Here’s the RND_textScramble code - download

How to use

You place this code anywhere in an FLA that will get it on the stage - at authoring time or run time, doesn’t matter if it’s buried in some nested MovieClip. That last line of code findTextFields(_root) passes a reference of the _root of the SWF to start the recursion.

If you would like to know more about the details of the recursive code then visit part 1 from yesterday.

As the code recursivly goes through all the MovieClips on the stage at authoring time it is looking to see if there is anything in mc[p] that has the .text property, i.e. TextFields. If it finds one then it passes that TextField as a reference to the randomizeText() function.

randomizeText()

The randomizeText function could be a lot simpler by just picking from any random ASCII character. But I wanted to make it a little more subtle. So it checks each character to see what ASCII range it’s in so that it gets replaced with a ASCII character in the same range. So a capitalized letter gets replaced by some other random capitol letter, numbers become other random numbers, etc.

It’s a bit tedious to test everything so there’s an else at the end to catch anything that doesn’t fit.

That’s about it. Just sit back and watch your designer friends slap their foreheads and say, “What the FRAK!?!?!?”

Note: It’s probably not a good idea to do this to someone just before you go on a vacation. :-)

Disclaimer: I accept no responsibility if you get fired for using this.

If you’d like to see a full list of the ASCII characters check this page: http://www.ascii.cl/htmlcodes.htm


Practical jokes to play on Flash designers - randomize _x, _y position

July 5th, 2007 . by polyGeek

You know how designers are so particular about placing assets just right? Have you seen them zoom in on the stage, select a MovieClip, and start changing it’s position by a few tenths of a pixel this way or that?

How would you like to play a little practical joke and learn some recursive code in the process?

Here’s the idea: write a function that receives a reference to a MovieClip. It takes that MovieClip and runs a for-in-loop on it looking for other MovieClips. If it finds one it passes that MovieClip back to itself - recursion. During the process it bumps all the MovieClips it finds by a few pixels this way or that, randomly.

Place this code anywhere in your friend’s/co-worker’s/victim’s FLA and give it a start by passing a reference to the _root to the recursive function.

All this happens at runtime so all those assets on the stage at authoring time will be pushed around in random directions. Madness will ensue. :-)

Here’s the code:

Here’s what the view of the stage in the Flash authoring tool. Notice that everything is lined up on the grid lines. The gray grid lines are shapes and so are not affected by the bump function.

before random bumping

Here’s the SWF after the MovieClips have been bumped around. You can download the FLA here.

The bump() function receives three arguments: a reference to the MovieClip to move, the max amount to change the _x coordinate - dx - and the max amount to change the _y coordinate - dy.

So if you want to change the amount of movement then change the parameters that are passed. I find that something like 0.5 or so for each works pretty well. Annoyance will vary depending on obviousness and the time it takes to figure out what’s going on. :-)

I take no responsibility if you get fired for playing this practical joke. As a suggestion: don’t place this code in some designer’s FLA and then go on vacation.

Perils of recursion

Recursion can be an extraordinarily powerful tool but you must handle it with care. If you are writing functions that call themselves you need to have one mantra firmly committed to memory:

Save, then publish. Save, then publish. Save, then publish.

Why, you may ask? Because there is no better way to crash a program, or computer, than writing recursive functions or methods that don’t end. That’s the real key. Making sure that you break out of the recursion.

The example here is very straight forward. But others may not be. Take for instance the Lightning class that I wrote. You don’t want to know how many times I entered into an endless loop while testing that code.

You should take at least the same precautions when writing recursive code as you do when installing a new application on your system:

  • Save everything that’s open
  • Close every application that isn’t needed
  • Always save before publishing (your mantra)
  • Wear a hazMat suit
  • Make sure your life insurance policy is up to date

Okay, those last two may be overkill but you get the idea.

Tomorrow I’ll have a variation on this idea that is just as insidious.


Pre-Object Oriented Programming in Actionscript, part 1

July 5th, 2007 . by polyGeek

Introduction

This series of articles are not intended to teach you object oriented programming. They are intended to teach you the framework and syntax around OOP. This is like the Pre-Calculus class you took before taking Calculus. It makes things a lot easier down the road. At least that’s my hope.

Pre-Object Oriented Programming

The problem with learning to apply OOP practices in your Actionscript is that it’s a radical departure from your existing workflow. Unless you have time to sit down and peruse Colin Moock’s Essential Actionscript book, a few times, then it’s just a frakking pain to try to switch over all at once when you know full well you could go about doing things as you always have and get the job done.

Besides, who cares if you use OOP practices? It’s likely that no one but yourself will ever see your code. And if the end result is the same then why bother. Right?

Wrong. Adopting OOP coding into your projects will make them much easier to write in the first place, and they’ll be easier to update later.

Plus, you can put it on your resume and make more money. :-)

Note: I’m assuming here that you are comfortable with at least creating variables and the occasional function. If you know how to pass parameters to a function then you’re in good shape and if you know how to return a value from a function then everything’s shinny.

The best way to learn OOP in Flash Actionscript is to start with the syntax. Here is a list of some of the things you don’t need to know in order to get started.

  • instantiate,
  • public vs private,
  • instances,
  • objects,
  • constructors,
  • methods and properties,
  • design patterns

Yep, you heard me. Skip all that crap. You can pick that stuff up later.

No more _root

When you write code do you create variables on the _root, like say myVariable, and then refer to them from code inside MovieClips all located all over your FLA with: _root.myVariable? Well, no more.

Here’s what you do:

  1. Create an FLA and save it with any fileName you want.
  2. In the same folder as the FLA create a new .as file.
  3. Give the .as file a fileName of: Root.as
  4. Copy the code from below and paste it into the the Root.as file
  5. Make sure you save the Root.as file.
  6. In the FLA you created write this: trace(”from the Root class: ” + Root.myVariable);
  7. Publish and your Output panel should say: from the Root class: some value

Here’s the code for the Root class:

This is the first step into a much larger world. From anywhere in your FLA you can access the variables in your Root class just as you did with _root before. But now your variables are in a different file and easier to locate.

Lets go over this class file real quick.

  • The public static var is just what you put before each and every variable - variables are called properties in a class.
  • The :String or :Number are how you type your properties. You don’t have to do that but you really, REALLY should. Trust me on this. Just get used to it.
  • It is a convention, and one you need to follow, to make all class names start with a capital letter. So don’t make a class name such as myClass. It should be MyClass.

A few gotchas

Very, very important: the fileName of the class file and the name of the class must be identical. Except the class name does not get the .as extension. So if the filename of your class file is SomeClassName.as then the name of the class must be SomeClassName. If you named the class SomeClassname - lowercase n - it wouldn’t work.

I’ll tell you right now, this above issue gets me all the time. The problem is that you usually give the file a fileName before you give the class a class name. Once you start write your code you think to yourself, “This ClassName would be more descriptive if it were called SuchAndSuch. So you change it, then forget to change the fileName and everything’s a mess. You’ll may do this a few times yourself so be on the lookout.

You know how with FLA files you can publish them anytime to see your changes without saving first? Well, you can’t do that with .as files. If you change something in your .as file you have to save that file (Ctrl + s) before you can publish the FLA to see those changes.

You do not need to upload the .as files to the server in order for the SWF to work. When you publish your FLA file, creating the SWF, it takes the code in all your .as files and wraps it up into the SWF. Now the SWF can stand on it’s own.

If you share your FLA with someone then you have to give them all the .as files as well. The FLA won’t work without them.

What’s next

You put some variables - properties - in your class file. So what about functions, called methods in a class file? That’s just as easy to do. Here’s an example added to the code above.

Lines 17-19 make up the method doSomething. If from anywhere in your FLA you typed: Root.doSomething(); you would see the Output panel display “this is code running in a method of the Root class.”. Which doesn’t do much of anything. Lets add another one that’s a little more useful.

Take a look at lines 21-25. The method average2numbers receives to arguments: a and b. It takes those two numbers and adds them together, then divides by two and then returns that result. That’s why line 21 has :Number appended. That declares the type of value that the method will return.

So back in your FLA you can say something like this:

Line #1 says, I want to create a variable, of type Number, and I want it’s value to be equal to the result that comes from sending the parameters (2,6) to the method average2numbers in the Root class. Then line #2 just traces that result to the Output panel.

This should enhance your workflow right off the bat by giving you a place to put your variables and functions to get at them faster than if you placed them on the _root of your FLA.

In part 2 you’ll learn how to make those public parts private and create getters and setters.


News Flash: Ryan Stewart suffers face-ectomy due to over blogging

July 2nd, 2007 . by polyGeek

Ryan Stewart Blogged His Face OffTragedy struck the Adobe family today when Ryan Stewart, newly appointed Rich Internet Applications evangelist at Adobe.com, lost all of his facial features due to blogging his face off.

Doctors are uncertain about his long term prognosis. But they do fear that this is just the first case in what may become an epidemic.

Ryan remains upbeat and determined to not let this get in the way of his new duties at Adobe.com.

Our hopes and prayers are with you Ryan.