Be a Supporter!

AS3: Movement with Keys

  • 35,274 Views
  • 33 Replies
New Topic Respond to this Topic
TrueDarkness
TrueDarkness
  • Member since: Aug. 31, 2004
  • Offline.
Forum Stats
Member
Level 27
Blank Slate
AS3: Movement with Keys 2007-05-12 12:46:32 Reply

AS3: Main

Aha, my first AS3 tutorial! Let's begin!

Here's what you will be learning how to do using AS3:
Example

After struggling to find a way to make object movement using AS3 without the use of deltas code (which I refused to use =p) I finally found a simple way to do it, that I'd like to share in tutorial form, to help others understand.

So, first, open up a new AS3.0 flash document, and open the actions for the first frame.

The first thing you want to do, is define some variables for your arrow keys (up, down, left, right). So using strict-data typing (making things more specific for faster running), we set up our variables:

var varRight:Boolean = false;
var varLeft:Boolean = false;
var varUp:Boolean = false;
var varDown:Boolean = false;

So what we just did was defined 4 variables, eached named varArrowKeyHere
What a boolean is is a true/false argument. you can easily take out the :Boolean part, but it helps to run things even faster and make for less confusion in the Flash scripting.

The next thing we want to do is define some variables for the objects movement speed, like so:

var xspeed:Number = 5
var yspeed:Number = 5

xpseed and yspeed are not the only names you can use. You can call it whatever you'd like. Call them pickleLegs for all I care. The ":Number" is the same type of thing as :Boolean except it applies to numbers and not true/false.

Alright, so now our variables are done, horrah! Now for the harder part.

In AS3, almost everything as far as I know is done using functions. Functions are written the same way as in AS2 or 1 with a little extra bit added, depending on what you do with it.

So, what we want to do now is make a function that checks what keys are down. To do this, we just give the function a name and define what type of function it is. Observe:

function checkKeys(event:KeyboardEvent) {
This is the opening of our function. It is a function that I called "checkKeys" and it is a KeyboardEvent function, meaning it only works with interaction of the keyboard, which will be specifically defined later.

Now we can begin adding actions into the function, and complete it.

So, the easy way to check if a key is being pressed is using a method that involves the keyCode action. To do this, all you do is event.keyCode = #. What goes in # is up to you. You have to know what #'s equal what on the keyboard. In our case, we will be using 37, 38, 39, 40.
37 = left arrow key
38 = up arrow key
39 = right arrow key
40 = up arrow key.

So, what we want to do is make an if statement that checks if one of the above arrow keys is being pressed. Let's start with the right arrow key.

if (event.keyCode == 39) {
trace("Right key is down");
varRight = true;
}

What is happening in this bit of code is flash is checking to see if the right arrow key WAS pressed. Note the was. This method does NOT work like the Key.isDown() method used in AS2 or AS1, hence my struggle to work out this code ;)

Anyway, this method works as a variable, stating that if the arrow key is pressed, it "stays" pressed, in effect. But let's move on for now. Once it detects that he right arrow key (39) is pressed, it will give an output in the testing of the fla stating that the Right key is down. (NOTE: YOU CANNOT TEST THE FLA YET, YOU WILL GET ERRORS) Then, it defines the varRight variable as true. (The boolean is now true).

And now, just paste this code with the proper changes for the remaining 3 keys left.

if (event.keyCode == 38) {
trace("Up key is down");
varUp = true;
}
if (event.keyCode == 37) {
trace("Left key is down");
varLeft = true;
}
if (event.keyCode == 40) {
trace("Down key is down");
varDown = true;
}

Now, all that's left is to end the function, and close it with a }

Your function should now look like this:

function checkKeys(event:KeyboardEvent){
if (event.keyCode == 39) {
trace("Right key is down");
varRight = true;
}
if (event.keyCode == 38) {
trace("Up key is down");
varUp = true;
}
if (event.keyCode == 37) {
trace("Left key is down");
varLeft = true;
}
if (event.keyCode == 40) {
trace("Down key is down");
varDown = true;
}
}

So now that that's out of the way, we now have to have a function that makes the variables false if the key isn't pressed. To do this, we make another function, with the same method of coding, with a different name. Like so:

function keyUps(event:KeyboardEvent) {

Okay, easy, let's move on now. The next set of if statements work pretty much the same as before.

if (event.keyCode == 39) {
event.keyCode = 0;
varRight=false;
trace("Right key is NOT down");
}

That is saying that if the right arrow key is "stayed" as down, then the right arrow is not down and the variable varRight is false.

So now we just add the other 3 if statements and close the function like before. The function should now look like:

function keyUps(event:KeyboardEvent) {
if (event.keyCode == 39) {
event.keyCode = 0;
varRight=false;
trace("Right key is NOT down");
}
if (event.keyCode == 38) {
event.keyCode = 0;
varUp=false;
trace("Up key is NOT down");
}
if (event.keyCode == 37) {
event.keyCode = 0;
varLeft=false;
trace("Left key is NOT down");
}
if (event.keyCode == 40) {
event.keyCode = 0;
varDown=false;
trace("Down key is NOT down");
}
}

Alright, almost done! Now for the actual allowing of the movement.

Make a movie clip on the document and give it the instance name "player".

Create another function, this time instead of event:KeyboardEvent we simply put Event, for now it is a regular event that can be called with the function from anywhere.
So let's make our next function that I will call movement. This function is pretty self explanitory, so I won't bother going over it.

function movement(Event){
if (varRight == true) {
player.x += xspeed;
}
if (varUp == true) {
player.y -= yspeed;
}
if (varLeft == true) {
player.x -= xspeed;
}
if (varDown == true) {
player.y += yspeed;
}
}

There, fairly simple right? Now for the final step!
In AS3, to call functions and make things work, we have to use a method called addEventListener(). This isn't so hard to figure out, but it can be confusing for some...

Basically, we made 3 functions, so it's only logical that we have 3 "eventListeners" that we must "add".
The next 3 lines of code will look like this (following all the names I gave everything):

stage.addEventListener(Event.ENTER_FRAME, movement);
stage.addEventListener(KeyboardEvent.KEY_DOWN , checkKeys);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUps);

All these lines are doing is telling the stage (_root) to add an event listener with the specific event based upon what the function is, and then the given function.

Take the first line for example:

stage.addEventListener(Event.ENTER_FRAME, movement);
This tells the stage to add an event listener with the event lableed ENTER_FRAME (derived from AS2 and 1). Then, with a comma for separation, it adds the function named movement. So it's telling flash to call up the movement function, and have it work in an enter_frame event (think of enter frame as "every frame" which would be based on the frame rate).
And the same goes for the other events. So here's what the final code should look like:

Code (open in notepad or something)

And that's that! I hope it works for everyone and people use it :)

dELtaluca
dELtaluca
  • Member since: Apr. 16, 2004
  • Offline.
Forum Stats
Member
Level 20
Blank Slate
Response to AS3: Movement with Keys 2007-05-12 12:52:11 Reply

this is the exact way that mine works, only that mine deals with all keys using an array of boolean values, rather than seperate variables for each key :P but congrats on figuring it out yourself


using ShamelessPlug; NapePhysicsEngine.advertise();

BBS Signature
TrueDarkness
TrueDarkness
  • Member since: Aug. 31, 2004
  • Offline.
Forum Stats
Member
Level 27
Blank Slate
Response to AS3: Movement with Keys 2007-05-12 12:56:25 Reply

At 5/12/07 12:52 PM, dELtaluca wrote: this is the exact way that mine works, only that mine deals with all keys using an array of boolean values, rather than seperate variables for each key :P but congrats on figuring it out yourself

Haha, I know. I didn't mean to bash your code... It's fantastic. I even tried it, but it said it couldn't find the package :o? So, I made an alternative code without the use of package and class imports =p If ya don't mind. :)

Thanks though, I'm glad I did figure something out. I just thought a little bit and it came to me logically.

Here's a platformer example that I made using my script for all interested:
http://denvish.net/ulf/120507/46273_platforme r.php
Arrow keys, Up to jump

ShittyFlash
ShittyFlash
  • Member since: Apr. 13, 2007
  • Offline.
Forum Stats
Member
Level 05
Blank Slate
Response to AS3: Movement with Keys 2007-05-12 12:58:46 Reply

At 5/12/07 12:56 PM, TrueDarkness wrote: Here's a platformer example that I made using my script for all interested:
http://denvish.net/ulf/120507/46273_platforme r.php
Arrow keys, Up to jump

wow thats really good! thanks for the tut!

Kart-Man
Kart-Man
  • Member since: Jan. 7, 2007
  • Offline.
Forum Stats
Member
Level 27
Blank Slate
Response to AS3: Movement with Keys 2007-05-12 13:00:01 Reply

Hah, I guess AS3 is easier than it sounds. :D


postcount +=1;
Newgrounds Photoshop Headquarters || Don't use MS Paint! Use Aviary!
SING US A SING YOU'RE THE PIANO MAN

BBS Signature
TrueDarkness
TrueDarkness
  • Member since: Aug. 31, 2004
  • Offline.
Forum Stats
Member
Level 27
Blank Slate
Response to AS3: Movement with Keys 2007-05-12 13:01:43 Reply

At 5/12/07 01:00 PM, Kart-Man wrote: Hah, I guess AS3 is easier than it sounds. :D

Just takes a little getting used to. I had no idea what an eventListener was or how to code AS3. I practically cried when fooling with Flash 9 alpha AS3. But I'm slowly learning, getting better with practice :)

UnknownFear
UnknownFear
  • Member since: Feb. 27, 2004
  • Offline.
Forum Stats
Member
Level 37
Gamer
Response to AS3: Movement with Keys 2007-05-12 13:10:01 Reply

Nice work, TrueDarkness. The transition from programming is AS2 to AS3 isn't all that difficult to comprehend really. Just a little understanding.

Great tutorial, TrueDarkness.

CrazyLegs
CrazyLegs
  • Member since: Apr. 21, 2006
  • Offline.
Forum Stats
Member
Level 05
Blank Slate
Response to AS3: Movement with Keys 2007-05-12 14:01:35 Reply

I congragulate you on getting the movement smooth as isDown() was for AS2.

TrueDarkness
TrueDarkness
  • Member since: Aug. 31, 2004
  • Offline.
Forum Stats
Member
Level 27
Blank Slate
Response to AS3: Movement with Keys 2007-05-12 14:03:26 Reply

At 5/12/07 02:01 PM, CrazyLegs wrote: I congragulate you on getting the movement smooth as isDown() was for AS2.

Why thank you :)

RPGBandit
RPGBandit
  • Member since: Nov. 23, 2006
  • Offline.
Forum Stats
Member
Level 10
Blank Slate
Response to AS3: Movement with Keys 2007-05-14 18:27:49 Reply

At 5/12/07 02:03 PM, TrueDarkness wrote:
At 5/12/07 02:01 PM, CrazyLegs wrote: I congragulate you on getting the movement smooth as isDown() was for AS2.
Why thank you :)

as do I, I just figured it out, before you posted this, you beat me to it, no fair. I suppose I'll do buttons or something else.

jmtb02
jmtb02
  • Member since: Mar. 1, 2004
  • Offline.
Forum Stats
Member
Level 29
Game Developer
Response to AS3: Movement with Keys 2007-05-14 18:31:58 Reply

I miss Key.left :(.


Hi there!

BBS Signature
shazwoogle
shazwoogle
  • Member since: Sep. 27, 2004
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to AS3: Movement with Keys 2007-05-14 18:46:02 Reply

At 5/14/07 06:31 PM, jmtb02 wrote: I miss Key.left :(.

Key.left misses you. But seriously its just eventListeners I had to use them alot when platying with socketservers and the like. Just like AS2.0 AS3.0 inbuilt documentation rocks. Just look up events and it will tell you all you need to know. Then the rest is pretty much the same.

Tree-SkyLark-BCE
Tree-SkyLark-BCE
  • Member since: Aug. 6, 2005
  • Offline.
Forum Stats
Member
Level 35
Programmer
Response to AS3: Movement with Keys 2007-05-14 19:34:29 Reply

At 5/14/07 06:31 PM, jmtb02 wrote: I miss Key.left :(.

Key.LEFT, the constant, is still essentially the same. In AS3, it is Keyboard.LEFT. Along with all the other Key class constants, they move it to the Keyboard class.

Anyways, nice tutorial TrueDarkness. It provides nice, pleasing motion results.


BBS Signature
duhmAn
duhmAn
  • Member since: Jan. 7, 2004
  • Offline.
Forum Stats
Member
Level 08
Blank Slate
Response to AS3: Movement with Keys 2007-05-15 05:25:23 Reply

been looking for a tut for movement in as3 for some time, thanks for the tut, i guess as3 isn't all that hard

doondeka
doondeka
  • Member since: Mar. 25, 2007
  • Offline.
Forum Stats
Member
Level 20
Blank Slate
Response to AS3: Movement with Keys 2007-05-17 14:27:15 Reply

it will not work it just gives me this.**Error** Scene=Scene 1, layer=Layer 1, frame=1:Line 1: The class or interface 'KeyboardEvent' could not be loaded.
function keyUps(event:KeyboardEvent) {

Total ActionScript Errors: 1 Reported Errors: 1

atomic-noodle
atomic-noodle
  • Member since: May. 17, 2005
  • Offline.
Forum Stats
Member
Level 14
Blank Slate
Response to AS3: Movement with Keys 2007-05-17 14:57:19 Reply

Awesome tut, TD! Maybe I should try to pick up AS3. ;D

Even though i phail at AS2

iamcoreyg.com // campnorth
Need a website? music? graphics? CONTACT ME.

BBS Signature
Cecemel
Cecemel
  • Member since: Aug. 19, 2005
  • Offline.
Forum Stats
Member
Level 16
Blank Slate
Response to AS3: Movement with Keys 2007-05-17 15:17:29 Reply

now what if you just use

stage.addEventListener(KeyboardEvent.KEY_UP, keyup)
function keyup(Event:KeyboardEvent){
right = false
left = false
up = false
right = false
}

it seems to work with me :)


<3

Cecemel
Cecemel
  • Member since: Aug. 19, 2005
  • Offline.
Forum Stats
Member
Level 16
Blank Slate
Response to AS3: Movement with Keys 2007-05-17 15:24:20 Reply

noo, i meant without the keyCode = 0 things :S
else it'll just stop everything if you release a key


<3

TrueDarkness
TrueDarkness
  • Member since: Aug. 31, 2004
  • Offline.
Forum Stats
Member
Level 27
Blank Slate
Response to AS3: Movement with Keys 2007-05-17 15:32:44 Reply

At 5/17/07 03:24 PM, Cecemel wrote: noo, i meant without the keyCode = 0 things :S
else it'll just stop everything if you release a key

Well in effect it will work, because your converting the variables from true to false, making no motion. But if you want to add other keys of variables then you might have problems. It's better off to just add the = 0 and use the if statements to avoid problems in the future, and it's more specific, allowing Flash to make more accurate decisions based on the coding.

Cecemel
Cecemel
  • Member since: Aug. 19, 2005
  • Offline.
Forum Stats
Member
Level 16
Blank Slate
Response to AS3: Movement with Keys 2007-05-17 16:06:59 Reply

At 5/17/07 03:32 PM, TrueDarkness wrote: Well in effect it will work, because your converting the variables from true to false, making no motion. But if you want to add other keys of variables then you might have problems. It's better off to just add the = 0 and use the if statements to avoid problems in the future, and it's more specific, allowing Flash to make more accurate decisions based on the coding.

But the if without the = 0's, they don't make a difference to me. It's not much of a change, but why do more?


<3

archeris
archeris
  • Member since: Apr. 1, 2006
  • Offline.
Forum Stats
Member
Level 19
Blank Slate
Response to AS3: Movement with Keys 2008-07-20 19:54:12 Reply

Why do you add trace? It doesn't needs to use in any flash anyway.. It's jsut a some crappy As that isn't doing anything special. We can live happily without it.

cainine-k9
cainine-k9
  • Member since: Jul. 4, 2007
  • Offline.
Forum Stats
Member
Level 23
Blank Slate
Response to AS3: Movement with Keys 2008-07-22 13:08:02 Reply

At 7/20/08 07:54 PM, archeris wrote: Why do you add trace? It doesn't needs to use in any flash anyway.. It's jsut a some crappy As that isn't doing anything special. We can live happily without it.

Trace statements are usful in making sure that your eventlisteners are working and other stuff. ONce you dont need them, you can just change them to comments so they wont do anything.

falariem
falariem
  • Member since: Aug. 19, 2008
  • Offline.
Forum Stats
Supporter
Level 28
Programmer
Response to AS3: Movement with Keys 2008-09-19 03:30:06 Reply

Great tut! I've been looking for this.

Thank you very much!

james4562000
james4562000
  • Member since: Jan. 16, 2006
  • Offline.
Forum Stats
Member
Level 10
Blank Slate
Response to AS3: Movement with Keys 2008-12-22 16:48:43 Reply

it came up with errors with the player.....with the x and y i put all of the code in the first frame and i inserted a movie clip called player.... but that happened please pm me and help.


Cyruskahnstontin A.K.A Acid-Haze

imaganimation
imaganimation
  • Member since: Feb. 6, 2008
  • Offline.
Forum Stats
Member
Level 05
Blank Slate
Response to AS3: Movement with Keys 2009-01-27 13:35:11 Reply

haha shweet!

ur example reminded me of that atari 2600 game: adventure :P


BBS Signature
echeese
echeese
  • Member since: Mar. 17, 2005
  • Offline.
Forum Stats
Member
Level 09
Blank Slate
Response to AS3: Movement with Keys 2009-01-27 16:45:38 Reply

There is a small problem from what I can see with the code. With this, it seems like you'd go 1.4x faster when you go on a diagonall. This happens because the movement normal isn't normalized. As you end up going 5 pixels in both directions, they add up to have a magnitude of 7.07106781. This means you're going 7 pixels per frame, when you're supposed to go one. It's no big deal, but it's a common error i've seen all too often. See diagram for further explanation.

AS3: Movement with Keys


This is my new site: ryanspeets.com

jcbeartooth
jcbeartooth
  • Member since: Dec. 16, 2006
  • Offline.
Forum Stats
Member
Level 03
Blank Slate
Response to AS3: Movement with Keys 2009-08-25 23:00:28 Reply

thank you so much! i was trying to do movement but mine had a delay and was blocky...

this really fixed it! thank you!

1-ceth
1-ceth
  • Member since: Oct. 6, 2008
  • Offline.
Forum Stats
Member
Level 09
Blank Slate
Response to AS3: Movement with Keys 2010-03-08 11:00:58 Reply

It didnt work for me. I'm using a picture of a spaceship, and it just stays there. Does this code move the screen, not the player? This is the code that I have:

var varRight:Boolean = false;
var varLeft:Boolean = false;
var varUp:Boolean = false;
var varDown:Boolean = false;

var xspeed:Number = 5
var yspeed:Number = 5

function checkKeys(event:KeyboardEvent) {
if(event.keyCode == 39) {
trace("Right key is down");
varRight = true;
}
if (event.keyCode == 38) {
trace("Up key is down");
varUp = true;
}
if (event.keyCode == 37) {
trace("Left key is down");
varLeft = true;
}
if (event.keyCode == 40) {
trace("Down key is down");
varDown = true;
}
}
function keyUps(event:KeyboardEvent) {
if (event.keyCode == 39) {
event.keyCode = 0;
varRight=false;
trace("Right key is NOT down");
}
if (event.keyCode == 38) {
event.keyCode = 0;
varUp=false;
trace("Up key is NOT down");
}
if (event.keyCode == 37) {
event.keyCode = 0;
varLeft=false;
trace("Left key is NOT down");
}
if (event.keyCode == 40) {
event.keyCode = 0;
varDown=false;
trace("Down key is NOT down");
}
}
stage.addEventListener(Event.ENTER_FRAME , movement);
stage.addEventListener(KeyboardEvent.KEY _DOWN , checkKeys);
stage.addEventListener(KeyboardEvent.KEY _UP, keyUps);

I checked it with the syntax check and got no errors, but then when I hit publish preview, nothing would happen. Like I said, is it that it moves the background, not the player instance? I dont have a background yet, it's all white right now, so it's possible I'm not seeing iit because of that.

4urentertainment
4urentertainment
  • Member since: Aug. 1, 2008
  • Offline.
Forum Stats
Moderator
Level 13
Game Developer
Response to AS3: Movement with Keys 2010-03-08 11:26:28 Reply

At 3/8/10 11:00 AM, 1-ceth wrote: It didnt work for me. I'm using a picture of a spaceship, and it just stays there. Does this code move the screen, not the player? This is the code that I have:

This is a classic case of when people copy off a tutorial without knowing what it actually means.

Do you see any part in the code that moves anything? No.

j-enom
j-enom
  • Member since: Feb. 15, 2009
  • Offline.
Forum Stats
Member
Level 08
Blank Slate
Response to AS3: Movement with Keys 2010-03-19 13:45:26 Reply

Thanks man :D i was giving up on finding a tut, but thanks to you... REALLY thanks man great job