Monday, 15 June 2009

Keyboard controls in AS3

This is an update from the previous key controls tutorial. In this Flash tutorial you will learn how to control an object on the stage using the keyboard controls in Actionscript 3.0. The code used is very similar to the previous tutorial. I have used an image of a lemon as the control object which is available from: www.sxc.hu. If you want to move an object together in two directions then checkout Keyboard controls in AS3 part 2.


Keyboard controls in AS3

Step 1

Open a new Flash document.
Create an object you wish to control using the keyboard on the stage. Alternatively you can use an image as object like I have, by selecting File > Import > Import to Stage.




Step 2

Convert your object into a symbol by selecting F8.
Then give your symbol an appropriate instance name. eg lemon.




Step 3

On the timeline insert a new layer called “actions” then right click on the 1st frame and select Actions and enter the following code.

//1.Event listener to detect keyboard press.
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHit);

//2. Function to move the lemon object using keyboard key 
//with the movement speed at 5 pixels.
function keyHit(event:KeyboardEvent):void {
var speed:uint=5;
switch (event.keyCode) {
case Keyboard.RIGHT :
lemon_mc.x+=speed;
break;
case Keyboard.LEFT :
lemon_mc.x-=speed;
break;
case Keyboard.UP :
lemon_mc.y-=speed;
break;
case Keyboard.DOWN :
lemon_mc.y+=speed;
break;
}
}

Code:
1. This event listener detects when a keyboard key has been pressed and triggers the “keyHit” function.
2. This function uses a switch statement which determines what happens when a keyboard key is pressed. For example, if the right key is pressed the lemon object will move in the positive x-direction (right).

If you wish to increase the speed the object moves, you can change the speed variable 5.


Step 4

Test your keyboard control Ctrl + Enter. Now use the up, down, right and left keys on your keyboard to move the lemon object.



You should now be able to use keyboard controls in Actionscript 3.0.
Checkout keyboard controls-part 2 where you will learn how to move an object simultaneously in two directions. Feel free to contact me for any questions or comments and remember to subscribe. If you wish to limit the object to the stage boundaries then checkout this tutorial.

1 comments:

sister mary catherine 13 May 2011 19:23  

thanks! this was the third piece of code i tried to use and yours worked! :)

  COPYRIGHT © 2014 · ILIKE2FLASH · Theme by Ourblogtemplates

Back to TOP