The Mover class
The Mover class
The Mover class will simply move an object based on keyboard input. It is recommended that you close any files that you have open from the previous examples before proceeding.
1. Create a new Flash ActionScript 3.0 document and save the file as MoverExample.fla in the examples folder.
2. Draw a circle on Stage using the Oval Primitive tool (found within the Shape tools on the Toolbar). Hold
down the Shift key to constrain the proportions as you draw.
3. Select the circle and convert it to a MovieClip symbol (F8) named character. Make sure that the registration
point (the dark square in the 9-square grid within the Convert to Symbol dialog box) is in the center before clicking OK.
4. Create a new ActionScript class named Mover.
5. Save the ActionScript file as Mover.as in the examples/ com/anim/character folder.
6. Add the following highlighted code to have Mover sub- class MovieClip:
public class Mover extends flash.display.MovieClip {
7. Update the package statement with the following highlighted code to match the saved location of the
Mover.as file: package com.anim.character {
8. Add the following variable declarations immediately following the class declaration (i.e., just before the
public function Mover constructor line):
Chapter 3 Introduction to ActionScript Classes
protected var vx:int; protected var vy:int; protected var normalSpeed:uint = 5; protected var currentSpeed:uint = 0; protected var currentScaleX:Number;
Let’s review what you have so far. Steps 6 and 7 should
be pretty familiar to you following the visual effects class examples. In step 8, you’ve set up several proper- ties that will be accessed later in the code. All proper- ties use the protected keyword to guarantee that their
values can be altered by subclasses (and only by sub- classes). The vx and vy variables will store the x (left and right) and y (up and down) velocities, respectively. Both variables are strictly typed to the integer data type
The Flash Coordinate System
( int ). When strict typing a property, it is best to be as
specific as possible. It’s unlikely in the case of The Flash coordinate system starts at the top-left and corner of the Stage. Moving to the right increases
vx
vy that you’ll need your object to move at less than 1 the value of the x coordinate. Moving down pixel per frame (that’s quite slow), so integers will offer
increases the value of the y coordinate. sufficient precision. The integer data type also allows
negative values, which you’ll need for your object to move up or left.
The next variable, normalSpeed , stores the default speed. This variable is typed to the unsigned integer data type ( uint ). Unsigned integer values do not include negative numbers, so this works great for speed, which will always be a positive number (since it’s the absolute value of the velocity). You will use the speed, in combi- nation with the direction, to determine the velocities.
9. Add the following highlighted code to call the init method from the constructor:
public function Mover() { init(); }
10. Add the init method definition as follows below the constructor method: protected function init():void {
initSpeed(); currentScaleX = this.scaleX;
Animation with Scripting for Adobe Flash Professional CS5 Studio Techniques
this.addEventListener(Event.ADDED_TO_STAGE, ➥ onAddedToStage);
this.addEventListener(Event.REMOVED_FROM_ ➥ STAGE, onRemovedFromStage);
Much of this init method will look familiar from the effects classes. So, let’s just go through what’s new. An initSpeed method is called. This is separated into its own method to make this aspect of the Mover class simpler to override. The next line initializes the currentScaleX value based on the current x scale of the symbol used. The currentScaleX property will be useful in subclasses when you want to alter the hori- zontal direction/orientation of the character. The two addEventListener method calls are identical to those in the classes you’ve already written in this chapter.
11. Add the following method after the init method to initialize the currentSpeed property:
protected function initSpeed():void {
currentSpeed = normalSpeed; }
12. Add the following code after the initSpeed method: protected function onAddedToStage(e:Event):void {
this.stage.addEventListener(KeyboardEvent. ➥ KEY_DOWN, keyDown);
this.stage.addEventListener(KeyboardEvent. ➥ KEY_UP, keyUp);
startMoving(); }
protected function onRemovedFromStage(e:Event): ➥ void {
this.stage.removeEventListener(KeyboardEvent. ➥ KEY_DOWN, keyDown);
this.stage.removeEventListener(KeyboardEvent. ➥ KEY_UP, keyUp);
stopMoving(); }
Chapter 3 Introduction to ActionScript Classes
These methods have the same names as those used in the effects classes, but their content is different. The onAddedToStage method adds two event listeners to the
symbol’s stage property. These events fire when a key is pressed and when a key is released on the keyboard. The third line calls a (yet unwritten) method to start the Mover moving.
The onRemovedFromStage does the complete inverse of the onAddedToStage , removing the event listeners and calling a method to stop the Mover from moving.
13. Add the following three methods after the methods you’ve already written:
public function startMoving():void { this.addEventListener(Event.ENTER_FRAME, ➥ updatePosition); }
public function stopMoving():void { this.removeEventListener(Event.ENTER_FRAME, ➥ updatePosition); }
protected function updatePosition(e:Event):void { this.x += vx; this.y += vy;
The startMoving and stopMoving methods tend to the adding and removing of the ENTER_FRAME event. When the ENTER_FRAME event fires, it triggers the updatePosi- tion method.
The updatePosition method adds the x and y velocities to the current x and y coordinates to move the symbol on each frame.
14. Then add the following code for the two methods that will handle the keyboard events:
protected function keyDown(e:KeyboardEvent):void { if (e.keyCode == Keyboard.LEFT) { vx = -currentSpeed;
Animation with Scripting for Adobe Flash Professional CS5 Studio Techniques
} else if (e.keyCode == Keyboard.RIGHT) {
vx = currentSpeed; } else if (e.keyCode == Keyboard.UP) {
vy = -currentSpeed; } else if (e.keyCode == Keyboard.DOWN) {
vy = currentSpeed; } }
protected function keyUp(e:KeyboardEvent):void { if (e.keyCode == Keyboard.LEFT || e.keyCode == ➥ Keyboard.RIGHT) { vx = 0; } else if (e.keyCode == Keyboard.DOWN || ➥ e.keyCode == Keyboard.UP) { vy = 0; } }
The keyDown and keyUp methods utilize conditional logic to respond differently based on which key was
pressed. The keyCode property of the e parameter stores the key that was pressed when the keyboard event was fired. The keyCode value can then be compared against values stored in the Keyboard class. In this case, you’re looking for the arrow keys: left, right, up, and down. This section of code utilizes else - if statements because the conditions are all mutually exclusive, since each event will reflect exactly one key press. The x or y velocity will then be set, depending on which key was pressed. The keyDown method uses the currentSpeed property as the basis for the velocities, and the keyUp method sets the values to 0.
15. Ensure that the following import statements are included just inside the package declaration: import flash.display.MovieClip;
import flash.events.KeyboardEvent; import flash.events.Event; import flash.ui.Keyboard;
Chapter 3 Introduction to ActionScript Classes
The completed Mover class should now read as follows: package com.anim.character {
import flash.display.MovieClip; import flash.events.KeyboardEvent; import flash.events.Event; import flash.ui.Keyboard;
public class Mover extends flash.display. ➥ MovieClip {
protected var vx:int; protected var vy:int; protected var normalSpeed:uint = 5; protected var currentSpeed:uint = 0; protected var currentScaleX:Number;
public function Mover() { init(); }
protected function init():void { initSpeed(); currentScaleX = this.scaleX; this.addEventListener(Event.ADDED_TO_ ➥ STAGE, onAddedToStage); this.addEventListener(Event.REMOVED_ ➥ FROM_STAGE, onRemovedFromStage); keyUp); }
protected function initSpeed():void { currentSpeed = normalSpeed; }
protected function onAddedToStage ➥ (e:Event):void { this.stage.addEventListener ➥ (KeyboardEvent.KEY_DOWN, keyDown); this.stage.addEventListener ➥ (KeyboardEvent.KEY_UP, keyUp);
Animation with Scripting for Adobe Flash Professional CS5 Studio Techniques
startMoving(); }
protected function onRemovedFromStage ➥ (e:Event):void {
this.stage.removeEventListener(KeyboardEvent. ➥ KEY_DOWN, keyDown);
this.stage.removeEventListener(KeyboardEvent. ➥ KEY_UP, keyUp);
stopMoving(); }
public function startMoving():void { this.addEventListener(Event.ENTER_ ➥ FRAME, updatePosition); }
public function stopMoving():void { this.removeEventListener(Event.ENTER_ ➥ FRAME, updatePosition); }
protected function updatePosition ➥ (e:Event):void {
this.x += vx; this.y += vy;
protected function keyDown ➥ (e:KeyboardEvent):void {
if (e.keyCode == Keyboard.LEFT) { vx = -currentSpeed; } else if (e.keyCode == Keyboard.
➥ RIGHT) {
vx = currentSpeed; } else if (e.keyCode == Keyboard.UP) { vy = -currentSpeed; } else if (e.keyCode == Keyboard.DOWN) { vy = currentSpeed;
Chapter 3 Introduction to ActionScript Classes
protected function keyUp(e:KeyboardEvent): ➥ void {
if (e.keyCode == Keyboard.LEFT || ➥ e.keyCode == Keyboard.RIGHT) {
vx = 0; } else if (e.keyCode == Keyboard.DOWN ➥ || e.keyCode == Keyboard.UP) { vy = 0; } }
16. Save your script, return to the MoverExample.fla docu- ment, and update the character symbol properties to
use the com.anim.character.Mover class.
17. Save your document and test the movie (Figure 3.28).
Figure 3.28 The Mover class allows the arrow keys to move the character instance.
In the test window, press and hold the arrow keys to move the character around the Stage. Notice that you can navi- gate your character right off the edge of the screen. The
Animation with Scripting for Adobe Flash Professional CS5 Studio Techniques
first subclass to the Mover class will prevent your character from leaving the screen.