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. Qaboomba says:

    Man, this is like the best tut ever seen.. Everything is well explain and man. I wish all tuts were like this. Cuz i’m kinda noob, and here everything is shown were it is.. man it rox!

  2. Wow,

    Excellent tutorial… looking forward to the others.

    Goodjob,
    -Duane A. Clay

  3. Lukas says:

    Hey Mike.
    Your tutorial is the best, and everything is working for me.
    I just want to know something.
    Instead of moving images with my keyboard,
    i tried moving animations.
    I figured all of that out, and now i have this.
    When you start the animation, you see my character standing (animation). When you press Left, you see my character walking (animation) to the left. But when you release the Left button, the animation keeps on playing, but it just stays on the same spot.
    Is there a way to switch back to the standing animation, when you release the Left-button?
    I’m kinda new to action-script :oops:

  4. Mike says:

    Hi Lukas,

    Your question is similar to another question above, where I tried to explain it briefly:

    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 left, you would use

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

    But for it to idle (i.e. stop animating), 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 when you are not moving. You would then add the same else statement after the code for the right movement. This should give you what your looking for.

    Since I’ve been getting several questions on this, I hope to add a new tutorial that explains this more fully, but until then, hopefully this helps you out.

    Thanks for reading,
    Mike

  5. lolsex says:

    wow u guys all suck no offense but y would u make a tut on the easiest thing to do ever and on im not joking

  6. Mike says:

    lolsex,

    We make tutorials for all levels. For many, this was not the easiest thing to do in the world. Everyone has to start somewhere. Maybe you have more experience, so this is easy for you, but at some point even you had to learn how to do that. Just because you did not find this tutorial helpful, there is no reason to bash it, it’s writer, or more importantly insult it’s readers.

    – Mike

  7. Miniman says:

    I’m new at Flash until I come upon this tutorial but I am having one problem when I try to move it left, up, or down, the animation doesn’t switch the images I fixed the code and everything so it works but the images just won’t switch. Please Help me :sad: :cry:

  8. Mike says:

    Hi Miniman,

    Sorry you’re having trouble with this tutorial. Not sure what the problem is. Are you getting any kind of errors in the output window? (the output window should automatically come up when you test the movie from Flash if there are errors).

    My first thought is you may be having the problems with quotes vs. smartquotes that some others were having. Check the “Update” paragraph under the first block of code above. Otherwise, you can try sending me your .fla file to contact@spitshine-design.com and I can try troubleshooting it for you.

    – Mike

  9. Joaquin says:

    Awesome tutorial! Thank You

  10. Miniman says:

    The thing is my dad is a website designer and he cannot figure it out. I will send u the flash file asap.

  11. Mike says:

    Hi Miniman,

    The problem you are having here is that you need to take what you have on Scene 1 in your sample file and place it in it’s own movie clip. Then, the ActionScript you have in frame 1 of your actions layer of your sample file needs to be attached to the mc you created (click on the mc, then open the actions panel and add the script, do not attach AS to a keyframe).

    I emailed you the file with the corrections. If you open the symbol “smiley” you should see what I did. Also, to make the smiley smaller, after you place the symbol to the stage, you can simply change the height and width in the Transform pallette.

    Hope this helps you out, but if you are still having problems, let me know.

    Also, you can always find the source files at the end of my tutorials to help you along with the tutorials.

    Thanks for reading,
    Mike

  12. rudydbooty says:

    lol pretty neat!!:shock::shock:

  13. granadaza says:

    este tutorial es simple e incluso explica a que se refieren los script de “enterframe” “this ” gracias

  14. Anthony says:

    Thanks for the tut mike. I’ve been working with PS for a while now and wanted to move on to flash and give it a try. I’ve been reading alot lately in hopes to get my website flash enabled or at least have some nifty flash buttons on it.

  15. wooo says:

    :mrgreen: thanks so much

  16. Vix says:

    Hmm.. I followed the guide correctly but My character isnt changing direction. Its moving but not changing the view

  17. Mike says:

    Hi Vix,

    Sorry you are having problems with this. If you can send me the file (contact@spitshine-design.com), I can try and take a look and see if I can’t find what might be wrong.

    Thanks for reading!
    – Mike

  18. Lelouch says:

    Great Tutorial!

    BUt i was wondering, i didnt want to use your character so i tried applying the tutorial to a animation of sprites walking. But, when I preveiw the flash, i cant get the character to stand still when no arrows are pressed, and move (while the sprite is moving his feet) accros the screen. D i need to change the actionscript to do this?

  19. Mike says:

    Hi Lelouch,

    I actually have gotten a few questions on how to do what your looking for. It’s something I’ve been trying to find time to do for a second tutorial for this. Unfortunately, I have been EXTREMELY busy… working full-time, new freelance projects, and to top it all off, I’m moving into a new apartment…. just haven’t found the time to sit and do some new tutorials in about 2 months! Things are starting to settle down now that summers over, so hope to have something up in the coming weeks.

    Sorry for the delay, and thanks for reading!
    – Mike

  20. serge says:

    i just started learning actionscript today and i’m trying to do a char in 2d that walks left and right and jumps up and down.

    i did same as tutorial except only put in left and right frames, and took out the 3rd line for the up and down movement script…except now the symbol is stuck facing to the right and won’t turn when it moves to the left, any suggestions?

  21. J - Dawg says:

    I played around with your code, I’m trying to have it excactly like yours, but when the arrows key moves the animation plays… this is what I got, but my problem is for some reason it doesn’t show the animation… Thanks!

    code:
    onClipEvent(enterFrame){

    if(Key.isDown(Key.RIGHT)){
    this._x += 5;
    this.gotoAndStop(RightRun);
    }else{
    stop();
    this.gotoAndStop(Right);

    }

    if(Key.isDown(Key.LEFT)){
    this._x -= 5;
    this.gotoAndStop(“LeftRun”);
    }else{
    stop();
    this.gotoAndStop(“Left”);

    }

    if(Key.isDown(Key.UP)){
    this._y -= 5;
    }

    if(Key.isDown(Key.DOWN)){
    this._y += 5;

    }

    }

  22. Antoan says:

    I made a code like this one, but it’s gotoAndPlay instead of gotoAndStop and it freezes at the first frame :cry:

  23. Antoan says:

    To: J – Dawg
    You should make it this.gotoAndStop(“RightRun”), not this.gotoAndStop(RightRun) (the “” are mssing in yours)

  24. J - Dawg says:

    Antoan,
    Thanks for helping! It’s weird like the left arrow key only works if the right one doesn’t have “”… I don’t know whats wrong. Hope someone can help :).

  25. Toranos says:

    To add animation, you will need to change a bit. For example, You will need to have a default pose, Which is usually posing forward, then four more poses, each, inside that frame, will have a movieclip, with your animation.

    Then this code in the main movieclip, your character..
    onClipEvent (load) {
    speed = 10;
    }
    onClipEvent (enterFrame) {
    if (Key.isDown(Key.UP)) {
    this._y -= speed;
    this.gotoAndStop(2);
    }
    if (Key.isDown(Key.DOWN)) {
    this._y += speed;
    this.gotoAndStop(3);
    }
    if (Key.isDown(Key.RIGHT)) {
    this._x += speed;
    this.gotoAndStop(4);
    }
    if (Key.isDown(Key.LEFT)) {
    this._x -= speed;
    this.gotoAndStop(5);
    }
    }

    Of course, you can change the speed.
    Hope you understood.

  26. majida says:

    hi
    how can i stop him from getting out of the screen while playing?
    thanks

  27. flywheelfly says:

    This works GREAT! Just what I was looking for. Thanks.

  28. This is great, thanks.

  29. oz says:

    ha…….. pretty cool tutz!! this whole site is jammed packed with awesome tutz and they tell you what and how sources are used… even an idiot like me can understand it lol :roll: now if I can keep my mind set on just one thing lol

  30. anD says:

    Cool tut. Thanks for the article.:smile:

  31. Andi says:

    In this code
    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”);
    }

    }
    you can see it says this.gotoAndStop(“down”) well it might not work for you because he has named hes frames to down left right.

    so to fix this just replace up with like this.gotoAndStop(5);
    then that should work just thought i point this out for noobs

  32. Mike says:

    Hey Andi,

    Yes, you are right, if you are having trouble, you can reference the frame number rather than naming the frame. However it is my recommendation to do this only as a trouble shooting measure. It is better practice to use frame labels. While it might be a little tougher to remember what you labeled things, and there is more risk of mistyping, using frame labels makes for a more flexible .fla. If you wanted to go in and add frames to the timeline, or move the frame at all, using labels alllows you to do this without having to go back and change the code.

    Of course it really all comes down to personal preference, but that’s my two cents.

    – Mike

  33. Silent Noise says:

    Hi

    That’s awesome man!
    nice tutorial but…

    The character is moving and all but the animation wont change even in the file i downloaded…

    i use Adobe flash CS4
    and this is the code in the downloaded file:

    // when the clip enters the frame, perform the code between the curly brackets
    onClipEvent(enterFrame){

    // if the right arrow key is pressed, perform the code between the curly brackets
    if(Key.isDown(Key.RIGHT)){
    // move this clip 5 pixels to the right
    this._x += 5;
    // go to and stop on the frame labeled “right”
    this.gotoAndStop(“right”);
    }

    // the the left arrow key is pressed, perform the code between the curly brackets
    if(Key.isDown(Key.LEFT)){
    // move this clip 5 pixels to the left
    this._x -= 5;
    // go to and stop on the frame labeled “left”
    this.gotoAndStop(“left”);
    }

    // if the up arrow is pressed, perform the code between the curly brackets
    if(Key.isDown(Key.UP)){
    // move this clip 5 pixels up
    this._y -= 5;
    // go to and stop on the frame labeled “up”
    this.gotoAndStop(“up”);
    }

    // if the down arrow is pressed, perfrom the code between the curly brackets
    if(Key.isDown(Key.DOWN)){
    // move this clip 5 pixels down
    this._y += 5;
    // go to and stop on the frame labeled “down”
    this.gotoAndStop(“down”);
    }

    // closes the on clip event code
    }

    And this is the code in my file:

    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”);
    }

    }

  34. Silent Noise says:

    and the movie clip is in four files (in my file)
    but in the other one it’s just one layer and one movieclip:neutral:

  35. Silent Noise says:

    ok i came to figure out i was working the whole thing in the scene not in a new symbol :p my bad.

    it works perfectly now:mrgreen:

  36. obb says:

    how do you add movie two it. e.g. so it could jump

  37. blue lady says:

    great! keep going.. :grin:

    very helpful.. :razz:

  38. pligg.com says:

    Flash Tutorial: Character Movement with Arrow Keys…

    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….

  39. Xen says:

    “To add animation, you will need to change a bit. For example, You will need to have a default pose, Which is usually posing forward, then four more poses, each, inside that frame, will have a movieclip, with your animation.”

    I don’t understand sorry, where do the default poses actually go? My sprite is working fine, apart from stopping it animating when in a stationary postition. Have followed both sets of instructions, but neither have worked. I put in an “idle” keyframe and the else statement and it worked in one direction, but then stopped the animation completely. When I put the else statement after all 4 directions, my sprite no longer walked, just slid. All I need is a push towards how to stop animating the sprite when the keys are not pressed.
    Great tut by the way, best one on the web!

  40. Mike says:

    Due to overwhelming response to this tutorial, comments for this post are closed. If you are having problems, please refer to other users comments above, as the issue may already have been addressed.

    Thanks for reading,
    Mike