Monday, September 26, 2011

AS2: Arrow Key/WASD Movement

Welcome to Tutorial #1, in this tutorial, I will show you how to make a character or a simple movie clip in your game move using the arrow keys and/or WASD.

First off, lets create a new document.
Select AS2 as the programming language.
Draw your character.
Once you have finished drawing your character select the entire shape, and
press F8 to convert it to a movie clip.
When prompted, give the movie clip a name such as "character" or "player" and
for the registration point, keep it in the center of the 9 squares.

*Hint: The registration point is basically the point of rotation. So in this case,
it is the center


After hitting "OK", open up the actions of the new movie clip by either pressing
F9, or right clicking it and selecting "Actions".

In the actions, type:

onClipEvent(load){
speed=4;
}
onClipEvent(enterFrame){
if(Key.isDown(Key.RIGHT)){
this._x+=speed;
}

if(Key.isDown(Key.LEFT)){
this._x-=speed;
}
if(Key.isDown(Key.UP)){
this._y-=speed;
}

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

Let's take a look at what this code means:


onClipEvent(load){
speed=4;
}


This means, increase the players coordinate values by 4 when any of the buttons are pressed.


onClipEvent(enterFrame){
if(Key.isDown(Key.RIGHT)){
this._x+=speed;


The first line opens up the basic Movie Clip start action function that repeats the action again and again
The second line checks to see if the right arrow key is pressed.
The third line says that if the right key is pressed, then increase the "x" coordinates on the stage by whatever the speed variable is. In this case "speed" is set to 4 pixels per frame.
The other keys are basically the same, just going in different directions:

this._x+=speed;
Right Key
this._x-=speed;
Left Key
this._y-=speed;
Up Key
this._y+=speed;
Down Key


Now, you are all done with arrow keys. But what if you want to use WASD to control the player? Simply change one piece of the coding:

When on the arrow key function, you use this:

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


On WASD function, you use this:

if(Key.isDown(68)){


So pretty much, the code for a letter or number on the keyboard is a number value. You can check number
values by visiting:
http://people.uncw.edu/tompkinsj/112/flashactionscript/keycodes.htm

Well, that's all for Tutorial #1! Thank you for reading and I hoped this helped you!

3 comments: