Saturday, July 26, 2008

[AS3]Arrow key movement

Here is a quick tut on how to make a movieclip movable using the arrow keys.
First we are gonna need to import some events:
import flash.events.*;

Now lets declare a variable for speed:
var speed:Number = 5;

Now a few variables which will tell us whether or not each button is pressed:
var right:Boolean = false;
var left:Boolean = false;
var up:Boolean = false;
var down:Boolean = false;

now we are going to add an event listener that listens for any key being pressed, one that checks for keys released and one for enter frame:
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);

Now you need to create the movie clip that we are going to make move. It can be any shape or size. Give it the instance name object_mc . Now lets see the key down function. Type this:
function keyDownHandler(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.RIGHT){
right = true;
}
if(event.keyCode == Keyboard.LEFT){
left = true;
}
if(event.keyCode == Keyboard.UP){
up = true;
}
if(event.keyCode == Keyboard.DOWN){
down = true;
}
}

This basically makes it so that when one of the variables is true, that button was pressed.
Now for the key up function :
function keyUpHandler(e:KeyboardEvent):void{
if(e.keyCode == Keyboard.RIGHT){
right = false;
}if(e.keyCode == Keyboard.LEFT){
left = false;
}if(e.keyCode == Keyboard.UP){
up = false;
}if(e.keyCode == Keyboard.DOWN){
down = false;
}
}

This makes it so that when the key is released, the variable returns to false. Without this, after pressing the button once, the movieclip would keep moving in that direction even after the key was released. Now make a movieclip. It can be any size or shape. Just give it the instance name "object_mc" without the quotes. Now for the enter frame function:
function enterFrameHandler(e:Event):void{
if(right){
object_mc.x += speed;
}if(left){
object_mc.x -= speed;
}if(up){
object_mc.y -= speed;
}if(down){
object_mc.y += speed;
}
}

This actually moves the movieclip while the key is held. You can make it move faster or slower by changing the speed variable. So, as you can see arrow key movement is pretty easy with AS3. Any questions, email me or post.

No comments: