Flash Game Design  
 
   
 
Tutorials Articles
   
       
 
 
Moving Movieclips using Keys with Acstionscript 3
A tutorial showing you how to move a movieclip using the arrow keys with as3

 

 
 
Step 1.
Following on from the tutorial to add a movieclip using as3, we will now write the code to make the MC (movieclip) move when the arrow keys are pressed.
 

Line 1 - 4 - Having created an symbol called player, and exported it for actionscript, a new instance of it is create and positioned on the stage.

Line 5 - Speed variable for the MC movement

 
Step 2.
 

Line 7 - 10 - Four variables are created to hold whether or not each arrow key is being pressed. For example, Up is being pressed, up will be true

 
Step 3.
 

Line 12 - A function to check if an arrow key is down (being pressed), using a keyboard event.

Line 13 - A swtich funciton is used to check which key is being pressed.

Line 14 - 16 - If the left key is pressed, set "left" to true and break (don't check the other keys)

Line 17 - 25 - Same as 14-16, but for the other arrow keys.

Line 27 - 28 - A default is set to break from the switch statement if anything else is pressed.

 
Step 4.
 

Line 32 - 50 - This function is similar to the previous one, but it checks if the arrow keys has bee in released. eg. If the left key is released, "left" is set to false.

 
Step 5.
 

Line 52 - So now that we have a function to find if a key has been pressed or released, we can now move the playerMc

Line 53 - 58 - If left is true deduct 5 pixels (speed) from the playerMC's current x position. If right is true, add 5 pixels to playerMc's current x position.

Line 60 - 68 - The same as above but for up & down along the y axis

 

 
Step 6.
 

Line 68 - 68 - Next we add listeners to the stage using the keyboard events (UP & DOWN), and the functions for each (keyDownCheck, keyUpCheck)

Line 69 - We also add a listener using the ENTER_FRAME and the movePlayerMc function. Using the ENTER_FRAME event will run the function at the frame rate of the movie.

 
Step 7.

Above is the enire code. Download Source

 
   
More Flash Tutorials
Funky Flash Site Glitter Graphic Jagged Transition
   
Bubble Flow Text Basic Flash Site Advanced Flash Site
Scroll Gallery Falling Star Text Drop Down Menu
     
Rotating Gallery Shooting Bullets XML menu
     
     
 
Site Copyright © 2006 - 2009 Nick DS. All rights reserved.