Flash Tutorial: Character Movement with Arrow Keys

Flash Tutorial: Character Movement with Arrow Keys

Level: This is a basic ActionsScript tutorial. As this is not an animation tutorial, a basic knowledge of the Flash user environment is assumed

Version: I will be using Flash CS3 and AS2 (athough tut is compatible with earlier versions of Flash) and instructions are for the Mac. Windows users would use the PC counterparts for specific instructions on Flash Menu/Shortcut instuctions.

Description: In this Flash tutorial, I will show you how to move a game character using the arrow keys, and have the character face in the direction that he is moving.

Demo:

This movie requires Flash Player 8

Let’s get started!

Select “File > New” (command-“N”) and select Flash File (ActionScript 2.0) to open a new Flash document file.

Save the file, and give it the appropriate name. I will call this “charMove_tut1″. Feel free to make the document dimensions (“Modify > Document or “command-J”) whatever you like, but I chose to use a size of 400 x 300 pixels.

The first thing we want to do is create a game character with 4 seperate states: left profile, right profile, front profile and back profile. Because this is not an illustration / animation tutorial, I will not be going through how to illustrate your character. Feel free to illustrate your own character, and convert each profile into it’s own symbol. For those beginners who do not want to illustrate their own character at this time, feel free to download the below .swf files (or jump to the source at the bottom of this page):

Front Profile: Download (right click on link and select “Save Link As”)

This movie requires Flash Player 8

Left Profile: Download

This movie requires Flash Player 8

Right Profile: Download

This movie requires Flash Player 8

Back Profile: Download

This movie requires Flash Player 8

—- ads by google —-

To import these files, open your Flash file, select “File > Import > Import to Library”, browse to where you saved the above files, select the files and click the “Import to Library” button. You should now see the 4 profiles as symbols in your Flash document Library (Window > Library (cmd-L)).

Once you have your character profiles ready (either by using mine or creating your own), we will need to place them in a movie clip symbol in order to control the movement. On frame 1 of our main movie timeline, select “Insert > New Symbol” (cmd-F8). This will bring up the “Create New Symbol” dialog box (Fig. 1). In the “Name” field, give your symbol an appropriate name (I chose “mc_character”, select the “Movie Clip” radial, and hit OK. This will automatically put you in the symbol editing mode for your new symbol. In your new symbol, create 2 new layers. Name the top layer “actions”, the second layer “labels” and the bottom layer “character”.

Extend your timeline to 20 frames. Select keyframe 5 for all 3 layers (you can shift click or click and drag), and insert a new keyframe (Insert > Timeline > Keyframe or F6). Do the same thing at frame 10 and 15. Click on keyframe 1 of our “labels” layer, and in the Properties window (Window > Properties > Properties or cmd-F3), give this frame a label of “right” (Fig. 2).

On frame 5, do the same thing, giving it a lable of “left”, frame 10 label “up”, frame 20 label “down”. Your timeline should now look similar to Fig. 3.

Note: Technically, we can make this movie clip only 4 frames, with frames 1-4 labeled the same as above. However, For the purposes of this tutorial, I felt it better to extend the frames in order to better illustrate the frame labels.

On frame 1 of your “character” layer, drag your right profile symbol to the stage and align it to the center. Tip: You can center align your symbols to the stage by using the Align palette (Window > Align or cmd-K (Fig. 4). Be sure the “To Stage” button is selected (it will be a darker shade of grey when selected) to align your sybols to the stage, deselecting this button allows you to align multiple symbols to each other.

On frame 5 of your “character” layer, drag your left profile symbol to the stage and align it to the center. In case you haven’t figured it out, do the same thing at frame 10 with the back profile symbol and frame 15 with the front profile symbol.

The last step is to add the ActionScript to our movie clip symbol. On the “actions” layer, click on frame 1, and add the following code to the Action panel (WIndow > Actions or alt-F9):

stop();

This simply stops our movie from playing through, since we only want it to change based on what key is pressed. Do the same thing at frame 5, 10, and 15 of our “actions” layer.

Our movie clip is now complete, so it’s time to add the ActionScript that will control our movement and the profile of our character.

Return to your main timeline. Drag your “mc_character” symbol from the library onto your stage. WIth your character selected, add the following code to the Actions panel:

onClipEvent(enterFrame){
if(Key.isDown(Key.RIGHT)){
this._x += 5;
this.gotoAndStop(“right”);
}

if(Key.isDown(Key.LEFT)){
this._x -= 5;
this.gotoAndStop(“left”);
}

if(Key.isDown(Key.UP)){
this._y -= 5;
this.gotoAndStop(“up”);
}

if(Key.isDown(Key.DOWN)){
this._y += 5;
this.gotoAndStop(“down”);
}

}

UPDATE: I’ve been finding several readers having trouble with doing a straight copy/paste of this code from the Web. I believe the issue lies in the quotation marks (”). When copying from the Web, it sometimes uses “smartquotes”. If you are getting an error on test regarding the quote marks, first step is to be sure you are using regular quotes (type them in instead of copy/paste from the Web site). If you are still having problems, feel free to drop me a comment and I will try my best to help resolve your issues. – Mike

That’s it! Go ahead and test your movie. What you shoud see is when you click on the arrow keys, your character not only moves in that direction, but faces that direction as well (up being backwards, down being forwards).

Now, let me try and explain the code:

onClipEvent(enterFrame){

On ClipEvent refers to the movie clip which this code is added to, the “enterFrame” is saying everytime our movie enters this frame of our main timeline, peform the actions between the curly brackets.

if(Key.isDown(Key.RIGHT)){

when the right arrow key is pressed, perform the actions within the curly brackets.

this._x += 5;

this. refers to the movie clip that this code is attached to. _x refers to the x position of this movie clip. If the right arrow is pressed, move the moviclip 5 pixels to the right (Tip: for faster movement, increase this number, for slower movement, decrease this number).

this.gotoAndStop(“right”);
}

Go to our frame labeled “right” in our movie clip symbol and stop on that frame. (Tip: Frame labels are case sensitive).

if(Key.isDown(Key.LEFT)){
this._x -= 5;
this.gotoAndStop(“left”);
}

This code is doing the same as above, but saying if the left arrow is pressed, move the clip 5 pixels to the left and go to our frame labeled “left”.

if(Key.isDown(Key.UP)){
this._y -= 5;
this.gotoAndStop(“up”);
}

This is doing the same as above, but saying if the up arrow is pressed, move the clip 5 pixels up (_y represents the y position of your clip) and go to our frame labeled “up”.

if(Key.isDown(Key.DOWN)){
this._y += 5;
this.gotoAndStop(“down”);
}
}

This is doing the same as above, but saying if the down arrow is pressed, move the clip 5 pixels down and to go our frame labeled “down”.

Thanks for reading, and I hope you found this tutorial useful. Source files are below, with commented code. As always, comments or questions are welcome. Check back soon for more expaned tutorials based on the idea of character movement.

Source Files (Flash 8): Flash Tutorial: Character Movement with Arrow Keys

Be Sociable, Share!

90 Comments so far:

  1. omfg says:

    :razz:

    ^lol noob^ no seriously thats good dude

  2. it keeps saying doublequote error on lines 14 and 19, 5 errors actionscript

  3. Mike says:

    Hi Mr. Palmer’s class student,

    Not sure why you would be getting an error like that… Be sure you are using quotes (“) instead of double apostrophe (‘). Also, you can always check the source file (link at the bottom of the tutorial) and see if that works without error.

    I would love to help you out, but I will need more information. If you can possibly post your code here or email me the file you are having trouble with (contact@spitshine-design.com), and I will try and trouble shoot it for you.

    – Mike

  4. Ash says:

    Wow it works! Thank you x

  5. Ash says:

    Btw I got the same error with the quotes, you are meant to use ” which is above the number 2, instead of two double apostrophe ‘ ‘

  6. Mike says:

    Hi Ash,

    Glad to see you got it working! You are right, you should be using quotes, not double apostrophes… I see that my comment looked a little confusing so I’ve updated.

    Thanks for reading.

    – Mike

  7. manoj says:

    :roll:
    Yes it works..

  8. i keep getting
    **Error** Scene=Scene 1, layer=Layer 4, frame=1:Line 1: Clip events are permitted only for movie clip instances
    onClipEvent(enterFrame){

    **Error** Scene=Scene 1, layer=actions, frame=1:Line 1: Clip events are permitted only for movie clip instances
    onClipEvent(enterFrame){

    Total ActionScript Errors: 2 Reported Errors: 2

    :lol::lol::lol::lol::lol:

  9. Mike says:

    Hi Nay-ger,

    Not sure exactly what the problem is, but it sounds like you added the code either to an image symbol, or to the main timeline actions…

    On the main timeline stage (scene 1), be sure you are only selecting the character movie clip symbol (clicking only once, you will see a blue bounding box around the object). Then, paste the onClipEvent etc. code in the Actions Panel.

    Another issue may be that you didn’t save your character as a “Movie Clip” symbol. Be sure that it is indeed a movie clip (there will be a little blue square icon next to the symbol name in the symbol Library).

    If you still have a problem, try downloading the source file (link at the end of the tutorial) and let me know if that works for you.

    Hope this helps, thanks for reading!

    – Mike

  10. ela says:

    wat do u mean by main timeframe??

  11. Mike says:

    Hi ela,

    “Main timeframe” is actually “main timeline”, and refers to the MAIN stage (“scene 1″ by default). What this means is, you should not be in symbol editing mode. To know where you are, there should be a little “breadcrumb” trail under your timeline (refer to Fig. 3 above) that might look similar to this:

    “Scene 1 > mc_symbol > img_symbol” (with little icons instead of the > symbols)

    In this case, “scene 1″ would be your main timeline (or main stage). To return to your “main timeline”, you would click on “Scene 1″.

    Hope that helps clear things up for you.

    Thanks for reading.

    – Mike

  12. Pradeep says:

    :lol:
    it worked after i changed the 2 apostaphe to double quotes
    its cool!!!
    thanks

  13. Komal says:

    Hey!

    I am facing a problem with running the code.
    I have modified the left,right,top and bottom images as movieclip symbols and my mc_character is a movieclip symbol too.

    While running, everytime I hit a different arrowkey, the image appears in the center of the screen instead of rotating from the previous position.

    Is this problem arising because I have saved all profiles(left,right,top and bottom) as movieclip symbols instead of graphics?

    Any help will really be appreciated.

    Regds
    Komal

  14. Mike says:

    Hi Komal,

    Hmmm… not sure what the problem would be…

    It should be fine to save each profile as a movieclip, but then all 4 movieclips would still need to be in one movieclip. The arrow keys would be moving the one movieclip that contains all your profiles. Does that make sense?

    If you can send me the file (contact@spitshine-design.com), or paste the as code here I could probably better help trouble shoot it for you. And of course you can download the source file (bottom of this tutorial), which might better help explain things.

    Thanks for reading, and let me know if you still have trouble.

    – Mike

  15. Dave says:

    :smile:Hi Mike, it didn’t go smoothly but with the comments other users left I worked it out, Thanks for posting

    Dave.

  16. Nannafish says:

    :sad: i cant do it… when i go on convert to symbol, go on movieclip, name it and press enter the properties doesnt come up :sad: also i know why its not working coz im a noob :mad: i cant do it!!!!!!!

  17. Mike says:

    Hi Nananfish,

    The properties window won’t come up automatically… You need to click on the symbol (on the stage) and choose “Window > Properties > Properties” and a palette with a “Properties” tab should show up (most likely underneath you flash stage.

    Hope this helps.

    – Mike

  18. Jesse says:

    1087: Syntax error: extra characters found after end of program. onClipEvent(enterFrame){

    Whats the problem?

  19. Mike says:

    Hi Jesse,

    Not sure what the problem is… I would need to see what your code looks like. Can you post your onClipEvent code here and I’ll see if I can figure out the problem.

    Thanks for reading.

    – Mike

  20. ash says:

    hey
    every thing works fine exept when i press any arrow key it wont change animation i have folowed your guildlines and still therers a problem plz help

  21. Mike says:

    Hi Ash,

    Not sure where your problem is without seeing it. If you can either paste the code you are using here, or send me the .fla file (contact@spitshine-design.com) I would be happy to try and troubleshoot it for you.

  22. Dan says:

    Thanks, one of the better beginner movement tutorials I’ve seen. :smile:

  23. dam says:

    thx..it work

  24. Okami says:

    i has a prob.

    **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 4: Syntax error.
    this.gotoAndStop(”right”);

    **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 9: Syntax error.
    this.gotoAndStop(”left”);

    **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 14: Syntax error.
    this.gotoAndStop(”up”);

    **Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 19: Syntax error.
    this.gotoAndStop(”down”);

    Total ActionScript Errors: 4 Reported Errors: 4

    no idea what to do, cuz i’m also a noob

  25. Mike says:

    Hi Okami,

    Sorry that it isn’t working for you. Not sure, but you may be having the same problem as some other readers in that when you copy/paste the code from the Web page, it uses what are known as smart quotes instead of regular double quotes. In your code, where ever you have quotes (“), make sure you are using regular double quotes (just delete and retype). Hopefully this helps.

    If you are still having problems, just let me know and I will try to help you solve the problem.

    Thanks for reading.

    – Mike

  26. Chris says:

    :mrgreen: awesome tutorial, but there’s an error with the down key, it won’t go down (even on your demo…) do you know how to fix it?

    (i’m a noob :P )

  27. Mike says:

    Hi Chris,

    Thanks for the props, but I’m not seeing a problem in my demo… If you can post the code here, I can take a look and see if I can find the problem. Not for nothing, but are you sure your keyboard is working?

    Thanks for reading.
    – Mike

  28. Okami says:

    k it woks now thnx :mrgreen:

  29. Okami says:

    hey i has another question. I wanted to put some epic music in there too…how do i do that?

  30. Mike says:

    Hi Okami,

    Adding music is outside the scope of this tutorial, but to get you started, you would simply import your sound file (the same way we imported our characters from this tutorial), and then add the sound file to a keyframe.

    Tip: it’s a good idea to add your sound file to it’s own movie clip. The sound file movie clip needs to have the same number of keyframes for the sound to play (you’ll see a blue squiggly line on the timeline to indicate sound). Then, simply add your movieclip to the main timeline and you’re all set.

    I hope this at least helps, but I’ll try to do a thorough tutorial on adding sound in the near future.

    Thanks for reading!
    – Mike

  31. Rog'er says:

    Hi Mike – I’ve followed these instructions but the “stop();” command doesn’t seem to work! The ninja just spins around (well, looks in each direction) repeatedly

  32. Mike says:

    Hi Rog’er,

    Hmmm.. not sure what the problem is… My first guess is to tell you to make sure you are adding the stop(); action to the frame and not the character image. (you will see a little “a” in the keyframe).

    Hope that helps.

    -Mike

  33. Roger says:

    It works perfectly… I had the same problem with the quotes, but just changing them it works Ok.

    Another problem that can be going on, is that the code is in the frame and not in the movie clip.

    Thanks:razz:

  34. Gandy says:

    it doesn’t work. i’ve put in the action script, and done it all right, but it just does the right profile, it moves, but doesn’t change which profile, so it’s just pointing right. everything else is fine.

  35. marc951 says:

    this happens to me

    **Error** Scene=Scene 1, layer=action, frame=1:Line 8: Syntax error.

    Total ActionScript Errors: 2 Reported Errors: 2

  36. Mike says:

    Hi Marc,

    Not sure, but you may be having the same problem with the quotes. See the “Update” in the tutorial below the first block of code above.

    If you still have a problem, let me know and I’ll try to trouble shoot it with you.

    – Mike

  37. jack says:

    hello Mike u tutorial is very helpful for me thank you :mrgreen::mrgreen: if u r free can u create a as3 tutorial? anyway thank you

  38. Oboe Passion says:

    Thank you so much!!!!!!!!
    It is really hard to find a good beginners tutorial:roll:
    I have just learnt HTML coding (how to make a website) and am looking to learn how to make games to go on my website:grin: This is a great tutorial with no action script errors *thank god* and just perfect a noob like me looking to learn the fundamentals.
    Again Thankyou so much :mrgreen:

  39. mansoor says:

    :wink:it very nice in short script big work.:lol:

  40. ivan says:

    :grin: nice

  41. trent says:

    I did this same code to a character I made, one that walks, and he runs in place whenever i don’t press the arrow key, but when I do, the running stops and he just moves as a still picture. What should I do?
    here’s the code i used to get him to go left and right (For a sidescrolling game):
    onClipEvent(enterFrame){
    if(Key.isDown(Key.RIGHT)){
    this._x += 5;
    this.gotoAndStop(“right”);
    }

    if(Key.isDown(Key.LEFT)){
    this._x -= 5;
    this.gotoAndStop(“left”);
    }
    }

    is there any way to get him to not walk when I don’t press the arrow key as in an idle position, and make him move and have the walking animation when I do press the arrow key?

  42. trent says:

    oh, and also, when I make him jump, using this code:
    if(Key.isDown(Key.UP)){
    this._y -= 5;
    this.gotoAndStop(“up”);

    how do I make him come back down? im such a noob…

  43. Mike says:

    Hi Trent,

    There are a couple different ways to do what you are asking here, but I think the easiest way in relation to this tutorial is to add in “else” statement to your arguments. For example, to move right, you have it correct:

    if(Key.isDown(Key.RIGHT)){
    this._x += 5;
    this.gotoAndStop(”right”);
    }

    But for it to idle, you would add the else statement directly after:

    else {
    this.gotoAndStop(“idle”);
    }

    Obviously, you would add a new keyframe labled “idle”, with the state that you want the character to be in. You would then add the same else statement after the code for the left movement. This should give you what your looking for.

    The jumping is a little bit trickier… You can similarly do in “else” statement, but you would also need to set your _y back to it’s originating point. (+=5). However, since when you hold the up key, it continually goes higher, when you release, it will only go back the 5 pixels. I’ll have to look into this more and try to give you a better explanation/solution, but hopefully this gets you started.

    Thanks for reading,
    Mike

  44. Aditya Jalihal says:

    awesome:grin::cool::grin::cool::cool::cool::cool::cool::cool::cool::cool::cool::cool::cool::cool::cool::cool::cool::cool::cool:

  45. Toby says:

    hi. I was just wondering… i’ve made a wall, to stop this dude from gonig through it. of course, he just goes straight through it. What is the code to stop him doing this? i heard it was sumin like

    on(rollOver”what you called him”){

    “watyoucalledhim” movespeed=0
    }

    but that doesn’t work :(

  46. Mike says:

    Hi Toby,

    Hmmm, the code example you’re asking about is not really right at all. First, onRollOver is a mouse action, and we aren’t controlling the character with a mouse, so that wouldn’t work. Second, we aren’t setting the movement with a “movespeed” variable, so setting that to “0” would not work either.

    What you would want to use here is a “.hitTest”… when I have some time I’ll try to give you a full explanation (coincidentally I’m working on a tutorial now that touches on hitTest). Check back in the next day or so and I should have something for you.

    Thanks for reading!

    – Mike

  47. rayraytea says:

    Hi Mike, thanks for the tutorial. Very nicely written.

  48. andrew says:

    Great tutorial

  49. […] Read the Tutorial: Flash Tutorial: Character Movement with Arrow Keys […]