FrozenHaddock Flash Games, Tutorials and Resources

19Mar/093

8-Way movement in AS3

Now, you'll have to bear with me on this one, (I'm still learning AS3 too) but I may well have an AS3 tutorial for you today!

Let's learn how to listen for keys, and how to react to keyboard input. In this example, how to move a player when the user hits the cursor/WASD keys. (Which I have shown you before in AS2)

I'll be putting all of this code on the frame (Sorry strict AS3 writers, but for now, it's frame coding for me!), I will however place the character from the library, leaving nothing on the stage.

Setting up the stage and character

After quickly setting up your stage (I have mine on 24fps, 550 by 400px, you can have yours however you like so long as it's an Actionscript 3 document), you'll need to draw your character. For the purposes of this tutorial I've drawn a face, but let's face it, I'm no artist. So I'm sure you can think of something more imaginative :)

Library / Linkage / Document Setup

Library / Linkage / Document Setup

Once you've drawn your character, you need to convert it to a movie clip and give it an appropriate name (Anything will do), then you can delete it from the stage. Don't worry, it's not gone. Hit CTRL+L to bring up your library (if it isn't already open) and you'll see it right there at the top.

Right click your object and hit linkage, changing the class to 'char' as shown above. This will let us reference it in our code.

Getting your character onstage

That's all the setup we need to do, so lets move onto the code shall we? Click on the first frame in your timeline, and hit F9 to open the actions panel if it's not open already. This is where we will be coding the entireity of your character's movement.

Actions Panel

Actions Panel

The first thing we're going to do is to bring our player onto the stage from the library, and set it's position onstage. Remember how we gave it a class 'char'? Well now's the time to use it.

  1. var myChar:char = new char();
  2. myChar.x = 275;
  3. myChar.y = 200;
  4. addChild(myChar);

Basically, what we're doing here is creating a new instance of our 'char' object, and giving it the name myChar. We then set it's x and y coordinates (Note that AS3 does not use _x,_y as AS2 did) before finally adding it to the stage with addChild. Go ahead and test your movie, see if everything's working as it should be.

Positioned

Positioned

Looks like it's going fine to me! We'd better get our character moving eh?

Keylisteners and keyCodes

Now, unlike AS2, AS3 does not have a built in function for checking if a key is down. Instead, it checks for when a key is pressed, and when it is released. To do this, we're going to have to use a special type of Event Listener, called a Key Listener. Two infact!

  1. stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownFunction);
  2. stage.addEventListener(KeyboardEvent.KEY_UP, keyUpFunction);

These are our Keylisteners. The top one waits until a key is pressed, and then runs a function, in this case (imaginatively) called 'keyDownFunction'. And yep, you guessed it, the bottom one waits for a key to be released and then runs 'keyUpFunction'. Now, maybe we'd better write those functions eh?

The two functions are alike, in that both will check the key pressed/released and then set a boolean for movement accordingly. (A Boolean being a variable that is either true, or false.) We'll know that your character should be moving if the corresponding key has been pressed, but not yet released, so that's what we'll check for.

First things first, we need to define our Boolean variables at the top of the code, and initially set them to false.

  1. var moveLeft,moveRight,moveUp,moveDown:Boolean = false;

That should do the trick! Now down to the function...

Our code so far

Our code so far

To define our function, we need this first line:

  1. function keyDownFunction(event:KeyboardEvent) {

This includes the function identifier (keyDownFunction) which we use to call it when it's needed.

Next, I've included this line. Not nessicarily needed for the game, it will send the corresponding keycode for the key you've pressed to the output panel. This comes in handy when working out what keyCodes you need to check for.

  1. trace("Key Pressed: "+(event.keyCode));

Traces make no difference to the final .swf file, but can be extremely helpful when debugging code! You can omitt this line if you wish to.

Now we get to the meat of the function, the iftests that check against the key you pressed, and act accordingly.

  1. if (event.keyCode==37||event.keyCode==65) {
  2. moveLeft=true;
  3. }
  4. if (event.keyCode==39||event.keyCode==68) {
  5. moveRight=true;
  6. }
  7. if (event.keyCode==38||event.keyCode==87) {
  8. moveUp=true;
  9. }
  10. if (event.keyCode==40||event.keyCode==83) {
  11. moveDown=true;
  12. }

You'll see that in AS3 I have referenced the actual keyCodes of the keys, rather than naming the cursor keys Key.LEFT/Key.RIGHT etc. I think AS3 enforces this, anyone who knows differently do leave a comment won't you? Memorising keyCodes isn't my forté, hence the trace line. Another notable difference from this to AS2 is that you can no longer use the AND or OR keywords in if statements, instead having to use && or || respectively.

The keyCodes here are those for WASD and the Cursor keys.

37 & 65 - Left Cursor & A
39 & 68 - Right Cursor & D
38 & 87 - Up Cursor & W
40 & 83 - Down cursor and S

The function will set the corresponding Boolean variable to true when the key is pressed.

Now for the function that's carried out when a key is released:

  1. function keyUpFunction(event:KeyboardEvent) {
  2. if (event.keyCode==37||event.keyCode==65) {
  3. moveLeft=false;
  4. }
  5. if (event.keyCode==39||event.keyCode==68) {
  6. moveRight=false;
  7. }
  8. if (event.keyCode==38||event.keyCode==87) {
  9. moveUp=false;
  10. }
  11. if (event.keyCode==40||event.keyCode==83) {
  12. moveDown=false;
  13. }
  14. }

Pretty similar to the firs one, the only difference being that it sets the Boolean to false when the right key is released.

Let's get it moving then, eh?

Because this is a tutorial, and it's here to teach you something (I hope!) then I'll introduce the AS3 enterFrame listener here too, and control the player movement from a function. Which we'll write now.

  1. function moveChar() {
  2. if (moveLeft) {
  3. myChar.x-=speed;
  4. }
  5. if (moveRight) {
  6. myChar.x+=speed;
  7. }
  8. if (moveUp) {
  9. myChar.y-=speed;
  10. }
  11. if (moveDown) {
  12. myChar.y+=speed;
  13. }
  14. }

This function is pretty self explanatory. If the boolean is true, it'll move the character in the correct direction by 'speed', which is a variable we should define at the start of the file.

  1. var speed:Number = 5;

There. All done right? Nope! We need to make sure this function runs every frame! So it's back to those Event Listeners again.

  1. addEventListener(Event.ENTER_FRAME, enterFrameFunc);

This listener will run the function identified as 'enterFrameFunc', every frame. Simple enough, so we'll just go and write that function to finish off our code:

  1. function enterFrameFunc(event:Event) {
  2. moveChar();
  3. }

Now you can test your movie and move your character with the WASD/Cursor keys, Huzzahs and Hurrahs!

Key Control in as3 swf

And I'll just paste the entire script for you copy-pasters... (You'll learn nothing, nothing!)

  1. addEventListener(Event.ENTER_FRAME, enterFrameFunc);
  2. stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownFunction);
  3. stage.addEventListener(KeyboardEvent.KEY_UP, keyUpFunction);
  4.  
  5. var moveLeft,moveRight,moveUp,moveDown:Boolean = false;
  6. var speed:Number = 5;
  7.  
  8. var myChar:char = new char();
  9. myChar.x = 275;
  10. myChar.y = 200;
  11. addChild(myChar);
  12.  
  13. function keyDownFunction(event:KeyboardEvent) {
  14. trace("Key Pressed: "+(event.keyCode));
  15. if (event.keyCode==37||event.keyCode==65) {
  16. moveLeft=true;
  17. }
  18. if (event.keyCode==39||event.keyCode==68) {
  19. moveRight=true;
  20. }
  21. if (event.keyCode==38||event.keyCode==87) {
  22. moveUp=true;
  23. }
  24. if (event.keyCode==40||event.keyCode==83) {
  25. moveDown=true;
  26. }
  27. }
  28. function keyUpFunction(event:KeyboardEvent) {
  29. if (event.keyCode==37||event.keyCode==65) {
  30. moveLeft=false;
  31. }
  32. if (event.keyCode==39||event.keyCode==68) {
  33. moveRight=false;
  34. }
  35. if (event.keyCode==38||event.keyCode==87) {
  36. moveUp=false;
  37. }
  38. if (event.keyCode==40||event.keyCode==83) {
  39. moveDown=false;
  40. }
  41. }
  42.  
  43. function moveChar() {
  44. if (moveLeft) {
  45. myChar.x-=speed;
  46. }
  47. if (moveRight) {
  48. myChar.x+=speed;
  49. }
  50. if (moveUp) {
  51. myChar.y-=speed;
  52. }
  53. if (moveDown) {
  54. myChar.y+=speed;
  55. }
  56. }
  57.  
  58. function enterFrameFunc(event:Event) {
  59. moveChar();
  60. }

So, that concludes this tutorial! You can grab the source .fla here, 'cause we're good like that. Please remember, this is as much a learning experience for me as it is for you, if you can see anywhere I've done something wrong, or in an odd way, or if you can improve upon it in any way, please feel free to! Comment below or hit the forums with any questions or comments you may have, and I hope this helps!

Comments (3) Trackbacks (0)
  1. Nice! This was a really clear tutorial. I like the way you set moveDown, moveUp etc. Booleans when the keys are hit and then move based on that later.

    One thing: you said “You’ll see that in AS3 I have referenced the actual keyCodes of the keys, rather than naming the cursor keys Key.LEFT/Key.RIGHT etc. I think AS3 enforces this, anyone who knows differently do leave a comment won’t you?” — actually if you “import flash.ui.Keyboard” then you can use Keyboard.KEY_LEFT, Keyboard.KEY_RIGHT, etc. Doesn’t contain letters though.

  2. Thanks! :) I’m glad it came out clear, I was worried it’d be babble :P

    And I see! I’ll have to try that. Can’t be doing with remembering keyCodes.

  3. Just an interesting glitch, when you press a key of the ASWD’s, then press its corresponding key on the arrow keys, the ASWD’s lose control and the arrow keys gain it. It works the other way around, too, but I don’t think it effects anything.


Leave a comment


No trackbacks yet.