ActionScript.org Flash, Flex and ActionScript Resources - http://www.actionscript.org/resources
Make your own reusable classes using Flash and AS3
http://www.actionscript.org/resources/articles/698/1/Make-your-own-reusable-classes-using-Flash-and-AS3/Page1.html
Jody Hall
My interest in Flash started mostly because of a Jib-Jab cartoon ("This Land") in 2004. I'm the author of a feature I call "Mazoons," which are a combination of mazes and cartoons. In 2002, I even had a book published, "Super Silly Mazes." I'm not a professional programmer, but making my mazes interactive by programming them with Flash has become a hobby/obsession of mine in recent years. My efforts so far can be seen at http://www.mazoons.com/Flash_mazes.htm.  
By Jody Hall
Published on November 22, 2007
 
Difficulty: Easy
This tutorial is intended for beginning programmers just starting to learn to use classes, or beginning to intermediate programmers migrating from Actionscript 2.0 to 3.0 that haven't done very much programming with classes yet. It will cover how to store your classes in your own packages, understanding the classpath, and how to write your first simple classes that are actually useful and reusable. The only prerequisite skills you need: The ability to create MovieClip symbols in Flash CS3, some knowledge of Actionscript 3.0's event listeners, the ability to browse your hard drive’s folder system, and the ability to create new folders.

Classes, Packages, and the Classpath

Let's suppose that in your programming experience, you know how to make a Movie Clip draggable with the mouse, and you also know how to write a routine to make a MovieClip respond to the arrow keys and move around the stage. Let's further suppose that you've done both of those tasks many times, and you get to thinking "Wouldn't it be great if I could just write one routine for each task, and then just apply it to future Movie Clips at will?" Enter reusable Classes!

The couple of classes that we'll write together are going to be really cool, but first let's set up a package to store our first classes, and set the classpath so that Flash can find them. This is something that I didn't understand for the longest time, but also something that becomes simple once you "get it."

Packages are just directories (or folders, if you prefer) on your hard drive. Inside the directories are stored one or more class files. The reasons you might want to store classes into separate packages are (1) mostly to avoid naming conflicts, and (2) to group similar classes together.

The key to understanding the whole package thing is to set up one folder on your hard drive as a "portal" directory. At least I think of it as being a portal, or an avenue, or a route, to the folders that lie beneath it. The location of it doesn't matter, it's entirely up to you, but this directory will be designated as being in the classpath. So, go ahead and create a new folder somewhere on your hard drive, and we'll tell Flash to add it to the classpath. I chose to call mine "Classes." Feel free to use that name, or substitute one of your own, because the name doesn't matter much, as it won't be used at all in the package statements of our classes, nor the import statements of our fla files.

There are two ways in Flash to designate a classpath. The first way is in the publish settings for the document, but this only works for one document at a time. I prefer the second way, which sets the classpath for all new documents. So, inside Flash, go to Edit, Preferences. In the Preferences dialog box, click "Actionscript" in the left pane. In the right pane, click the button that says "Actionscript 3.0 settings." In the Actionscript 3.0 Settings dialog box, click the button with the plus sign (+). Next, click the browse button (it looks like a target) so that you can browse your system to find the folder you just created. When you've located the folder, click OK on the browse dialog box. Finally, click OK on the Actionscript 3.0 dialog box, and the Preferences dialog box. Done!



Establishing Communication: TestClass

Now that you have a classpath folder set, let's start off by just writing the most simple class file there could ever be. It will simply trace a message to the screen. Mainly, this will be a test to make sure we've got communication with our classes, but also we'll also refine the folder structure a little bit by creating subfolders beneath our "portal" folder to store our classes in. Don't worry; it will all become clear as we go along.

Inside of Flash, click the File menu, choose "New" and then "Actionscript File." In the new Actionscript document's script pane, type the following:

[as]package com.mysite.testing {
public class TestClass {
public function TestClass() {
trace("TestClass working");
}
}
}[/as]
Note that the folders "com," "mysite," and "testing" don't exist yet, but that's okay. We will create them in the process of saving the file. Go to File, Save As. In the Save As dialog box, first navigate to the folder you created earlier as a "portal" directory. Next, find the "New Folder" button and click it to create a new folder (alternatively, right-click somewhere in the file/folder list and choose "New" then "folder."). Call the new folder "com." Double click the new com folder to enter it. Make a new folder inside of it called "mysite" (Here you may substitute the name of your own website if you want. If not, the name "mysite" will do just fine, until you get the hang of all this). Double click the mysite folder to enter it. Create a new folder called "testing." Double click testing to enter it. Finally, save the file as TestClass.as.

Wow! That was a lot of folder creation, and hopefully it doesn't seem too confusing. But here's the deal: Now your file's location matches the location spelled out in the package declaration. Note that the name of the "portal" directory is not included in this line, because that directory is flash's starting point, and that's exactly why I like to think of it as being a portal. It's the folder that flash already knows about, because we set it in the classpath, so all we need to be concerned about is organizing everything beneath that. The folders "com" and "mysite" will be the common denominators here (we'll always use them), but will remain empty, and the folders beneath "mysite" will be named according to the functionality of the classes inside them. Since we just wrote a TestClass, we just created a package for it called "testing," and we might use the "testing" package to store all the files we create where we test new things. Or you can feel free to delete it later. I just used it for an example.

Let's put the TestClass to the test and make sure it works. Choose File, New, and create a new Flash File (Actionscript 3.0) document. Click on the first frame of the timeline, and press F9 to go to the actions panel. Type the following two lines:
[as]import com.mysite.testing.TestClass;
var testClass:TestClass = new TestClass();[/as]

Press CTRL-Enter to test the movie. You should immediately get a message traced to the output window saying “TestClass working.” That’s because that instruction was written into the public function with the same name as the class. This special function is known as the constructor, and it runs immediately one time whenever an object is created from the class with external code using the “new” keyword. So, the constructor function is a good place to put the code that you want to have run automatically whenever a new object is created from your class. The next class we’ll write will be a good example of this.

It's also interesting to note here that since you have your own global classpath folder set, it's not even necessary to save the fla file anywhere! The folder that was set gives Flash an additional place to look for classes, and also an additional place to look when we tell it to import something.


First useful class: ClipDragger

Now we're going to write our first truly useful class. Choose File, New, then Actionscript File. This class, when applied to a MovieClip, will make that MovieClip draggable with the mouse. This is a relatively simple thing to do using frame code in a fla file, and chances are you already know how to do it, but I chose it for an example because it is so simple, and we're just getting the hang of classes and adding complexity very gradually.

Type the following into the script window:
[as]package com.mysite.mouse {
public class ClipDragger {
public function ClipDragger(clip:MovieClip) {
trace("ClipDragger working");
}
}
}[/as]

Now click File, Save As. Navigate to the mysite folder and create a new folder called "mouse." Double click the mouse folder to enter it, and save the file as ClipDragger.as. Next, open a new Flash document. Let's test ClipDragger and see if we get our trace message this time:

[as]import com.mysite.mouse.ClipDragger;
var clipDragger:ClipDragger = new ClipDragger();[/as]

When you run this, you will get the following error message:
1046: Type was not found or was not a compile-time constant: MovieClip.

When you’re just starting with classes, you will get a lot of error messages. They’re a fact of life, but as you progress and learn what the problems are, you’ll get fewer and fewer, and you’ll know what to do about them. But you know what? Although you might never get away from them completely, they’re actually a good thing, because this prevents your code from being compiled with a mistake in it. In this case, the problem is that we’ve told Flash that we’re going to be sending the name of a MovieClip as a parameter, and, since our class is in a separate package from everything else, Flash acts as though it’s never heard of a MovieClip! Imagine that! So the solution is to add an import statement that imports the MovieClip class. Change the code in the AS file to the following (add the import line):
[as]
package com.mysite.mouse {
    import flash.display.MovieClip;
    public class ClipDragger {
        public function ClipDragger(clip:MovieClip) {
            trace("ClipDragger working");
        }
    }
}[/as]
Save the file, and try running the fla file again. Oops, another error message:
1136: Incorrect number of arguments. Expected 1.

The problem here is that we indicated in our class file that we would be passing in the name of a MovieClip instance to drag, but neglected to do it. So, now let’s fix that. In the fla file, draw something on the stage, anything at all will do. Select it and convert it to a MovieClip symbol. Give it an instance name of “myClip” and change the code to the following:

[as]import com.mysite.mouse.ClipDragger;
var clipDragger:ClipDragger = new ClipDragger(myClip);[/as]
(NOTE: Make sure you've drawn something, converted it to a MovieClip symbol, that it's on the stage, and that you've given it an instance name of "myClip" in the properties panel)

This should run without any errors, and give you an output window that traces the message “ClipDragger working.” Sorry if all of this seems overly simplistic, but my aim here is to start with simple examples and build complexity very gradually. Besides, if you’ve never programmed with classes before, this should all be starting to make sense to you, possibly for the first time ever. Our ClipDragger class now has the proper communication with the fla file, but obviously, it doesn’t drag anything yet. Let’s move on and add that functionality.

But first, a brief aside: The purpose of any class is to create objects from that class, and objects have properties and methods. Probably you’ve been programming using Flash’s built-in classes for some time now, and you know how to create an object of a class, then call upon the properties and methods of that class to make the instantiated object do things. Each object gets its own copy of every property and method, and the public properties and methods are the ones that we can access from external code.

This is going to be the same thing, only now we’re creating our own class that we can instantiate objects from, and call upon our own properties and methods. So the first modification to ClipDragger will be to give it a property. This property will be of the MovieClip type, and it will be a reference to the MovieClip object that we pass in as a parameter. To achieve this reference, first we declare in the variable list that there is such a property, then in the constructor, we set that property to be equal to the MovieClip that’s passed in.

Note that the name that we give the property ought to be different than the name that we use for a parameter, so we’ll just call the property by the same name, only precede it with an underscore. This way, the two names (“clip” and “_clip") are different, and we can tell at a glance that the one with the underscore is the one that belongs to the class as a private variable. We make the property private because all of the operations that will be performed on it will happen inside this class. There is no reason to expose it to external code. So our class code becomes:

[as]package com.mysite.mouse {
    import flash.display.MovieClip;
    public class ClipDragger {
        private var _clip:MovieClip;
        public function ClipDragger(clip:MovieClip) {
            _clip = clip;
        }
    }
}[/as]
So, every instance of ClipDragger will have as one of its properties a reference to whatever MovieClip instance we pass to it as a parameter. Let’s go on to make our passed in clip draggable. This can be done simply by adding event listeners to it, which you probably already know how to do in a fla, but may have never tried in the context of a class before, but it’s basically exactly the same thing. The event listeners will be added right inside the constructor, so that every time a new instance of this class is created, the clip that is passed as a parameter will automatically have all the event listeners added to it that it needs to give it drag and drop behavior. First let’s attempt to make the clip drag whenever the mouse is pressed down on it:
[as]package com.mysite.mouse {
    import flash.display.MovieClip;
    public class ClipDragger {
        private var _clip:MovieClip;
        public function ClipDragger(clip:MovieClip) {
            _clip = clip;
            _clip.addEventListener(MouseEvent.MOUSE_DOWN, drag);
        }
        private function drag(event:MouseEvent) {
            _clip.startDrag();
        }
    }
}[/as]
Save this file, then run the fla again. I said “attempt” above because I knew this would generate yet another error:
1046: Type was not found or was not a compile-time constant: MouseEvent.

The problem is that we’re attempting to use mouse events without first importing them. As you write your classes, you’ll start to get the hang of realizing when you need to import another class, and you’ll soon learn all their locations as well. In this case, we need to add this line:

[as]import flash.events.MouseEvent;[/as]

Add that import statement to the AS file, and save it again. Each time you alter an AS file, you need to save it, or else when you run the fla, it won’t be using the new changes you’ve made. CTRL-S is a helpful keyboard shortcut for File/Save. Also, you may or may not ever have noticed this, but when a file has changed and it hasn’t been saved in its current form, there is a little asterisk next to the file’s name on the tab in the Flash authoring environment. This is typical of many other applications besides Flash. If you already knew it, sorry to bore you with it, but if you didn’t, you’ve got to admit it’s a handy indicator.

So when you save that file and run the fla, this time you should have a draggable clip. Okay, yes it’s draggable, but it doesn’t drop when you release the mouse button. We’ll add that next.

Here’s another aside: You may already know that to create the drop functionality, you use the MouseEvent.MOUSE_UP event. You may also know that you don’t necessarily want to add this event to the clip itself, but rather to the stage. This is because the user of your program might drag the clip at a high rate of speed, then release the mouse button and, if at that point, the mouse cursor isn’t actually over the clip, the MOUSE_UP event won’t register and the clip will continue dragging. Adding the event to the stage instead takes care of this problem.


ClipDragger continued: Accessing the Stage from the class
But how do we get a reference to the stage from inside our class file? There are several ways of doing this, but the easiest way in this case is just to get it from the clip we just passed in. Every display object (of which our MovieClip is one) has a property called “stage” that’s an instance of the Stage class. In other words, every display object “knows” what stage it’s on. So, revise the ClipDragger class as follows:
[as]package com.mysite.mouse {
    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    public class ClipDragger {
        private var _clip:MovieClip;
        public function ClipDragger(clip:MovieClip) {
            _clip = clip;
            _clip.addEventListener(MouseEvent.MOUSE_DOWN, drag);
            _clip.stage.addEventListener(MouseEvent.MOUSE_UP, drop);
        }
        private function drag(event:MouseEvent) {
            _clip.startDrag();
        }
        private function drop(event:MouseEvent) {
            _clip.stopDrag();
        }
    }
}[/as]

Now that you have drag and drop functionality in your class, you can now simply apply it to any MovieClip you want, even apply it to multiple MovieClips. Go back to the fla file, and create two more MovieClips. Make a circle MovieClip and a square MovieClip, and give them those as instance names. Next, add the code to create new instances of your class to make those clips draggable too. So the code in the fla file now becomes:

[as]import com.mysite.mouse.ClipDragger;
var clipDragger:ClipDragger = new ClipDragger(myClip);
var clipDragger2:ClipDragger = new ClipDragger(circle);
var clipDragger3:ClipDragger = new ClipDragger(square);[/as]

The above few lines of code will make all three clips exhibit drag and drop behavior. Run the fla file and test it out. You should now be able to drag and drop all three MovieClips, quite independently of each other.

You may notice when you run this that there are a couple of other refinements we ought to make. For one thing, there’s no hand cursor when we mouse over the clips. This is an easy fix—just set the _clip’s buttonMode property to true, and we’ll do that right in the constructor, by adding this line:

[as]_clip.buttonMode = true;[/as]

The other thing is that whatever clip we’re currently dragging ought to come to the front of Flash’s stacking order. You may have noticed that one of the clips will pass behind another when it’s being dragged, and that just looks weird. This is also fairly easy to fix, you just need to add this line to the mouse down event:

[as]_clip.parent.setChildIndex(_clip, _clip.parent.numChildren - 1);[/as]

In plain English, this line is telling our clip’s parent (which is the main timeline of the fla) to set our clip’s display index to a certain value. However many children there are, set the index to that number minus one. This just involves knowing that Flash’s Display Object Containers (of which the main timeline is one) keep an internal list of whatever display objects are added to them. This list starts it’s numbering at 0, so the number of children minus one would give you the highest index, no matter how many children there are. And setting the index to the highest number has the effect of bringing our clip to the front.

So, here’s our completed class file:
[as]package com.mysite.mouse {
    import flash.display.MovieClip;
    import flash.events.MouseEvent;
    public class ClipDragger {
        private var _clip:MovieClip;
        public function ClipDragger(clip:MovieClip) {
            _clip = clip;
            _clip.buttonMode = true;
            _clip.addEventListener(MouseEvent.MOUSE_DOWN, drag);
            _clip.stage.addEventListener(MouseEvent.MOUSE_UP, drop);
        }
        private function drag(event:MouseEvent) {
            _clip.parent.setChildIndex(_clip, _clip.parent.numChildren - 1);
            _clip.startDrag();
        }
        private function drop(event:MouseEvent) {
            _clip.stopDrag();
        }
    }
}[/as]
When you test and run the fla this time, you’ll get a hand cursor when you hover the mouse over each clip. When you press the mouse button down to drag a clip, that clip will come to the front and overlap any other clips there might be. And that concludes the discussion of this first example. Let’s move on to create our next truly useful class, wherein we’ll move a MovieClip around the screen using the keyboard.



Second useful class: KeyMover
Open a new Actionscript file. Type the following in to the script pane:
[as]package com.mysite.keyboard {
    import flash.display.MovieClip;
    public class KeyMover {
        private var _clip:MovieClip;
        public function KeyMover(clip:MovieClip) {
            _clip = clip;
        }
    }
}[/as]
This just sets up the basic structure of our file, similar to the last example. You already know that you’re going to be passing in the name of a MovieClip, so we import that class. We create a private variable _clip, and in the constructor, set it to be equal to the clip that’s passed as a parameter, like we did before. What’s new here is that we’re going to save this file into a different package we’ll name “keyboard.” So, go to File, Save. Inside the “Save As…” dialog box, navigate to com, then mysite. Create a new folder and call it “keyboard.” Double click the new folder to enter it, then save your file as “KeyMover.as.”

Next, create a new Flash file. Create a simple circular MovieClip symbol and give it an instance name of “ball.” This will be the clip that we move around the screen using an instance of our class. Click on the first frame of the timeline and open the actions panel. Type in the following:

[as]import com.mysite.keyboard.KeyMover;
var keyMover:KeyMover = new KeyMover(ball);[/as]

This establishes communication between our fla file and the class file, and creates a new instance of our class file. This time, having newfound confidence in our skills, we didn’t bother to trace a message from the constructor to make sure it works. We just know. We’ll leave this fla file for now, and do some more work on our class.

So far all our class does is receives a MovieClip as a parameter. If we want to move that clip with the keyboard, we obviously need to add listeners to listen for keyboard presses and releases. If you’ve programmed these listeners before, you know that they need to be added to the stage. This is because if you add them to the ball, and the ball doesn’t happen to have “focus” in your flash application, they won’t work. So, take my word, we add the keyboard listeners to the stage. Once again, we’ll use the passed in clip to get a reference to the stage. Add these lines to the constructor:

[as]_clip.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
_clip.stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);[/as]

The functions referred to, “keyPressed” and “keyReleased” don’t exist yet, and we’ll write them next. But first, since we used the KeyboardEvent class in the above, that class will need to be imported. So add the following line just below the line that imports MovieClip:

[as]import flash.events.KeyboardEvent;[/as]

And all is well, and we won’t get an error message this time. Hopefully you see a pattern here: every time you want to use a class that resides in a different package, you will have to import it.

Next, let’s go on to write the handler functions. Add them in just under the constructor, and make them private functions. Here’s our class so far with those added in:
[as]package com.mysite.keyboard {
    import flash.display.MovieClip;
    import flash.events.KeyboardEvent;
    public class KeyMover {
        private var _clip:MovieClip;
        public function KeyMover(clip:MovieClip) {
            _clip = clip;
            _clip.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
            _clip.stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
        }
        private function keyPressed(event:KeyboardEvent) {
           
        }
        private function keyReleased(event:KeyboardEvent) {
           
        }
    }
}[/as]
These functions will get called whenever any key is pressed or released. We’re only interested in the arrow keys, though. So how do you write your functions to only respond to those particular keys? The answer is that the information for which key was pressed or released is contained in the event object that our handler function receives as a parameter, and the property we need is called “keyCode.” So inside our handler, event.keyCode will contain the keyboard code of the key that was pressed or released. We need to test the value of this property so we can tell if the key that was pressed is one of the ones we’re interested in. This value is a number, and if we want to, we can take the trouble to learn what those numbers are. However, there is an easier way.

It so happens that many of the key codes that are most commonly used have already been written into a class for us as constants. All we need to do is import and use this class. This is the Keyboard class (what else?), and it’s located in the flash.ui package (if you didn’t know that, a good place to find it out is in the help files), so add this line to the import statement block:

[as]import flash.ui.Keyboard;[/as]

Now, for example, instead of having to know the numeric value for the right arrow key, we can just use the constant Keyboard.RIGHT to test whether a particular keypress is the right arrow key:

[as]if(event.keyCode == Keyboard.RIGHT) {
//do something
}[/as]

This is because the constant Keyboard.RIGHT contains the actual numeric value we need. Others might prefer to just use the numeric values of the keys directly, and you can do that if you want. I prefer to just import the class, use the constants provided, and save myself the trouble of memorizing the numbers.

Next, to keep track of which keys are being pressed, we’re going to create four Boolean variables, and define them at the beginning of our class:

[as]private var rightArrow:Boolean;
private var leftArrow:Boolean;
private var upArrow:Boolean;
private var downArrow:Boolean;[/as]

Now, here’s the logic: When the user presses a key, if it’s the right arrow key, set rightArrow to true. When the user releases a key, if it’s the right arrow key, set rightArrow to false. And the same for the other keys. So our handler functions can be written like so (here’s the entire class so far):
[as]package com.mysite.keyboard {
    import flash.display.MovieClip;
    import flash.events.KeyboardEvent;
    public class KeyMover {
        private var _clip:MovieClip;
        private var rightArrow:Boolean;
        private var leftArrow:Boolean;
        private var upArrow:Boolean;
        private var downArrow:Boolean;
        public function KeyMover(clip:MovieClip) {
            _clip = clip;
            _clip.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
            _clip.stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
        }
        private function keyPressed(event:KeyboardEvent) {
            if(event.keyCode == Keyboard.RIGHT) {
                rightArrow = true;
            }
            if(event.keyCode == Keyboard.LEFT) {
                leftArrow = true;
            }
            if(event.keyCode == Keyboard.UP) {
                upArrow = true;
            }
            if(event.keyCode == Keyboard.DOWN) {
                downArrow = true;
            }
        }
        private function keyReleased(event:KeyboardEvent) {
            if(event.keyCode == Keyboard.RIGHT) {
                rightArrow = false;
            }
            if(event.keyCode == Keyboard.LEFT) {
                leftArrow = false;
            }
            if(event.keyCode == Keyboard.UP) {
                upArrow = false;
            }
            if(event.keyCode == Keyboard.DOWN) {
                downArrow = false;
            }
        }
    }
}[/as]
Now the only thing left to do is write a function that moves the clip. This requires continuous action, so we’ll use the ENTER_FRAME event. The listener for this event needs to be added to the stage as well, so add this line in the constructor, just under everything else:

[as]_clip.stage.addEventListener(Event.ENTER_FRAME, moveClip);[/as]

Now, since we can’t use the Event class without importing it, add this import statement to the end of the import statement block:

[as]import flash.events.Event;[/as]

Now, we’ll write the moveClip function. Add it to the end of your list of functions:
[as]private function moveClip(event:Event) {
    if (rightArrow) {
        _clip.x += speed;
    }
    if (leftArrow) {
        _clip.x -= speed;
    }
    if (upArrow) {
        _clip.y -= speed;
    }
    if (downArrow) {
        _clip.y += speed;
    }
}[/as]
Add this line to your variable list at the top of the class:
[as]private var speed:uint = 10;[/as]

By creating a separate speed variable, we have one convenient place in the class where we can change the speed and make it apply instantly to all directions. Now the KeyMover class should be fully functional to move the ball around the screen. Be sure to save it, then go back to the fla file, and test your movie. You should get no errors, and be able to move your ball MovieClip around the screen with the arrow keys.

You’ll find, however, that you can also run it right off the edge of the screen. That’s because we didn’t restrict its movement in any way. We could either make the ball stop at the edge of the screen, or we could make it wrap the screen. Let’s add in some code to make it wrap the screen, as that’s kind of a cool effect.








KeyMover continued: Wrapping the screen
We’ll add the code to wrap the screen to KeyMover's "moveClip" function.

First, however, go back to the fla file and make sure that the registration point of the ball MovieClip is in the upper left hand corner, as our programming statements in the class are going to assume that. If it's not, double-click the MovieClip in the library to edit it. All of the contained graphics should be selected automatically, but if not, make sure you select them all. Then, in the align panel (press CRTL-K for the panel if it's not already around), make sure the "to stage" button is selected. In the first row of buttons, click the align left and align top buttons. Done! Go back to scene 1, and we'll leave the fla file for now.

Now, back to the moveClip function in our KeyMover class. Let’s take on the right arrow key first. The logic goes like this: If the user is pressing the right arrow key, and if the _clip’s x property exceeds the width of the screen, change the _clip’s x property to the left side of the screen (which would be 0), minus the width of the _clip. The width of the screen is contained in stage.stageWidth. As before, we’ll use the _clip’s stage property to get a reference to the stage:
[as]if (rightArrow) {
_clip.x += speed;
if (_clip.x > _clip.stage.stageWidth) {
_clip.x = -(_clip.width);
}
}[/as]
Save the class, go back to the fla and test the movie. You’ll get screen wrapping when you hold down the right arrow key. Pretty cool, eh? The coding for all the other arrow keys follow similar logic. Here's the entire KeyMover class, inlcuding the revised moveClip function, which now provides screen wrapping in all four directions:
[as]package com.mysite.keyboard{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event;
public class KeyMover {
private var _clip:MovieClip;
private var rightArrow:Boolean;
private var leftArrow:Boolean;
private var upArrow:Boolean;
private var downArrow:Boolean;
private var speed:uint = 10;
public function KeyMover(clip:MovieClip) {
_clip = clip;
_clip.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
_clip.stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
_clip.stage.addEventListener(Event.ENTER_FRAME, moveClip);
}
private function keyPressed(event:KeyboardEvent) {
if (event.keyCode == Keyboard.RIGHT) {
rightArrow = true;
}
if (event.keyCode == Keyboard.LEFT) {
leftArrow = true;
}
if (event.keyCode == Keyboard.UP) {
upArrow = true;
}
if (event.keyCode == Keyboard.DOWN) {
downArrow = true;
}
}
private function keyReleased(event:KeyboardEvent) {
if (event.keyCode == Keyboard.RIGHT) {
rightArrow = false;
}
if (event.keyCode == Keyboard.LEFT) {
leftArrow = false;
}
if (event.keyCode == Keyboard.UP) {
upArrow = false;
}
if (event.keyCode == Keyboard.DOWN) {
downArrow = false;
}
}
private function moveClip(event:Event) {
if (rightArrow) {
_clip.x += speed;
if (_clip.x > _clip.stage.stageWidth) {
_clip.x = -(_clip.width);
}
}
if (leftArrow) {
_clip.x -= speed;
if (_clip.x < -(_clip.width)) {
_clip.x = _clip.stage.stageWidth;
}
}
if (upArrow) {
_clip.y -= speed;
if (_clip.y < -(_clip.height)) {
_clip.y = _clip.stage.stageHeight;
}
}
if (downArrow) {
_clip.y += speed;
if (_clip.y > _clip.stage.stageHeight) {
_clip.y = -(_clip.height);
}
}
}
}
}[/as]

That concludes the KeyMover class. There are, of course, other refinements that could be made. For example, I usually prefer to use the Timer class instead of the ENTER_FRAME event to provide continuous action, as you can create motion that’s smoother and way less dependent on the movie’s frame rate, especially if you also use the TimerEvent class's updateAfterEvent() method. But I wanted to keep this tutorial fairly simple and basic, and if you want to, you can go on to create that. Or, hit me up for the class file, and I’d be glad to share it with you.

If you’ve made it this far in the tutorial, and you’ve actually created the two useful classes outlined above (TestClass doesn't count, haha!), here’s a little side benefit for you:. In your fla file that you used for KeyMover, let’s make the ball a member of both of the classes we’ve made. Change the code in the first frame of the fla to this:

[as]import com.mysite.keyboard.KeyMover;
import com.mysite.mouse.ClipDragger;
var keyMover:KeyMover = new KeyMover(ball);
var clipDragger:ClipDragger = new ClipDragger(ball);[/as]

Test the movie. You’ll find that now the ball movie clip is being controlled by both classes! You can click and drag the MovieClip, and you can also move it around with the arrow keys. How cool is that? The MovieClip is totally separate from the code that controls it, and it’s being controlled by two separate blocks of code simultaneously!

I hope you’ve enjoyed this tutorial, and I hope I’ve helped spark your imagination as to the potential of using classes in your programming. Because this is truly just the tip of the iceberg! Happy coding!