Newgrounds.com — Everything, By Everyone.

Checking login status…

USERNAME:

PASSWORD:

Logging in…

Logged in as:
.
Logging out…
Inbox My Account Log Out


Forum Topic: AS3: Movement with Keys

(1,358 views • 21 replies)

This topic is 1 page long.

<< < > >>
None

TrueDarkness

Reply To Post Reply & Quote

Posted at: 5/12/07 12:46 PM

TrueDarkness EVIL LEVEL 27

Sign-Up: 08/31/04

Posts: 4,718

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 :)


None

dELtaluca

Reply To Post Reply & Quote

Posted at: 5/12/07 12:52 PM

dELtaluca LIGHT LEVEL 20

Sign-Up: 04/16/04

Posts: 4,936

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

My social worker says im special!

BBS Signature

None

TrueDarkness

Reply To Post Reply & Quote

Posted at: 5/12/07 12:56 PM

TrueDarkness EVIL LEVEL 27

Sign-Up: 08/31/04

Posts: 4,718

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


None

ShittyFlash

Reply To Post Reply & Quote

Posted at: 5/12/07 12:58 PM

ShittyFlash EVIL LEVEL 05

Sign-Up: 04/13/07

Posts: 59

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!


None

Kart-Man

Reply To Post Reply & Quote

Posted at: 5/12/07 01:00 PM

Kart-Man NEUTRAL LEVEL 22

Sign-Up: 01/07/07

Posts: 2,961

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


None

TrueDarkness

Reply To Post Reply & Quote

Posted at: 5/12/07 01:01 PM

TrueDarkness EVIL LEVEL 27

Sign-Up: 08/31/04

Posts: 4,718

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 :)


None

UnknownFear

Reply To Post Reply & Quote

Posted at: 5/12/07 01:10 PM

UnknownFear FAB LEVEL 32

Sign-Up: 02/27/04

Posts: 5,565

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.


None

CrazyLegs

Reply To Post Reply & Quote

Posted at: 5/12/07 02:01 PM

CrazyLegs LIGHT LEVEL 05

Sign-Up: 04/21/06

Posts: 123

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


None

TrueDarkness

Reply To Post Reply & Quote

Posted at: 5/12/07 02:03 PM

TrueDarkness EVIL LEVEL 27

Sign-Up: 08/31/04

Posts: 4,718

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 :)


None

RPGBandit

Reply To Post Reply & Quote

Posted at: 5/14/07 06:27 PM

RPGBandit EVIL LEVEL 10

Sign-Up: 11/23/06

Posts: 626

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.


None

jmtb02

Reply To Post Reply & Quote

Posted at: 5/14/07 06:31 PM

jmtb02 LIGHT LEVEL 28

Sign-Up: 03/01/04

Posts: 5,459

I miss Key.left :(.

NOM NOM NOM NOM NOM

BBS Signature

None

shazwoogle

Reply To Post Reply & Quote

Posted at: 5/14/07 06:46 PM

shazwoogle NEUTRAL LEVEL 10

Sign-Up: 09/27/04

Posts: 2,608

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.


None

Tree-SkyLark-BCE

Reply To Post Reply & Quote

Posted at: 5/14/07 07:34 PM

Tree-SkyLark-BCE LIGHT LEVEL 28

Sign-Up: 08/06/05

Posts: 194

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

Happy

duhmAn

Reply To Post Reply & Quote

Posted at: 5/15/07 05:25 AM

duhmAn NEUTRAL LEVEL 08

Sign-Up: 01/07/04

Posts: 11

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


Questioning

doondeka

Reply To Post Reply & Quote

Posted at: 5/17/07 02:27 PM

doondeka EVIL LEVEL 12

Sign-Up: 03/25/07

Posts: 42

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

you never regret what you do until it gets in the face of death but its to late to opolgize your going to hell and il be your host...

BBS Signature

None

atomic-noodle

Reply To Post Reply & Quote

Posted at: 5/17/07 02:57 PM

atomic-noodle LIGHT LEVEL 13

Sign-Up: 05/17/05

Posts: 1,512

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

Even though i phail at AS2

None

Cecemel

Reply To Post Reply & Quote

Posted at: 5/17/07 03:17 PM

Cecemel LIGHT LEVEL 15

Sign-Up: 08/19/05

Posts: 770

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 :)

i <3 you


None

Cecemel

Reply To Post Reply & Quote

Posted at: 5/17/07 03:24 PM

Cecemel LIGHT LEVEL 15

Sign-Up: 08/19/05

Posts: 770

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

i <3 you


None

TrueDarkness

Reply To Post Reply & Quote

Posted at: 5/17/07 03:32 PM

TrueDarkness EVIL LEVEL 27

Sign-Up: 08/31/04

Posts: 4,718

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.


None

Cecemel

Reply To Post Reply & Quote

Posted at: 5/17/07 04:06 PM

Cecemel LIGHT LEVEL 15

Sign-Up: 08/19/05

Posts: 770

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?

i <3 you


None

archeris

Reply To Post Reply & Quote

Posted at: 7/20/08 07:54 PM

archeris EVIL LEVEL 16

Sign-Up: 04/01/06

Posts: 60

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.


None

cainine-k9

Reply To Post Reply & Quote

Posted at: 7/22/08 01:08 PM

cainine-k9 NEUTRAL LEVEL 11

Sign-Up: 07/04/07

Posts: 15

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.


All times are Eastern Daylight Time (GMT -4) | Current Time: 04:46 PM

<< Back

This topic is 1 page long.

<< < > >>
You need a Grounds Gold Account to post on the NG BBS! If you don't have one, click here to sign up now! It's fast, free, and easy — and opens up tons of great NG features!