Flash Essential

AS3 Guide Keyboard Events

Sep 15th 2008
3 Comments
respond
trackback

What are Keyboard Events?

Well it's simple really keyboard events allow our applications to react to a key being hit on the keyboard. This can help increase the usability of your application and is especially handy if you are creating a game which requires direction with the arrow keys.

Show Navigation || Hide Navigation

Below we have a square on the stage that we've created in actionscript. We can move the square by using the up, down, left and right arrow keys.

Make sure you click on the square first.

Let's go through the code in the application

First we dynamically create a square, give it some properties and add it to the stage.

var square:Sprite = new Sprite();
addChild(square);
square.graphics.beginFill(0×222222);
square.graphics.drawRect(0,0,100,100);
square.graphics.endFill();
square.x = stage.stageWidth/2-square.width/2;
square.y = stage.stageHeight/2-square.height/2;

stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyPressed);

function KeyPressed(evt:KeyboardEvent):void {
switch (evt.keyCode) {
case Keyboard.UP :
square.y -= 5;
break;
case Keyboard.DOWN :
square.y += 5;
break;
case Keyboard.LEFT :
square.x -= 5;
break;
case Keyboard.RIGHT :
square.x += 5;
break;
}
}

When using keyboard events make sure you add the event listener to the stage instead of the object. Inside the parameters we use tell the application what we are listening for. In this case we are listening for a KeyboardEvent and the KeyboardEvent we are listening for is a KEY_DOWN event. We give the event listener a unique name of our own in this case we've used KeyPressed, finally we close off the parameters and finish with a semi-colon.

var square:Sprite = new Sprite();
addChild(square);
square.graphics.beginFill(0×222222);
square.graphics.drawRect(0,0,100,100);
square.graphics.endFill();
square.x = stage.stageWidth/2-square.width/2;
square.y = stage.stageHeight/2-square.height/2;

stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyPressed);

function KeyPressed(evt:KeyboardEvent):void {
switch (evt.keyCode) {
case Keyboard.UP :
square.y -= 5;
break;
case Keyboard.DOWN :
square.y += 5;
break;
case Keyboard.LEFT :
square.x -= 5;
break;
case Keyboard.RIGHT :
square.x += 5;
break;
}
}

Now we want our square on the stage to move up, down, left and right when we press the respective keys. We need to create a function for our KeyPressed event listener but inside our function we create a switch statement to determine what the function should do when a certain key is pressed. Inside our parameters we have the argument evt.KeyCode this gets the key code for the key that was pressed to trigger the event. A key code is a numeric value that identifies the key that was pressed. Inside each statement you'll notice we have Keyboard.UP, Keyboard.DOWN ect… This is to select what key we want to use for the application, we always type keyboard first to enter the keyboard class then we select the respective key. We then change the squares X and Y properties to move the square the direction we what it to move for that particular key strike.

var square:Sprite = new Sprite();
addChild(square);
square.graphics.beginFill(0×222222);
square.graphics.drawRect(0,0,100,100);
square.graphics.endFill();
square.x = stage.stageWidth/2-square.width/2;
square.y = stage.stageHeight/2-square.height/2;

stage.addEventListener(KeyboardEvent.KEY_DOWN, KeyPressed);

function KeyPressed(evt:KeyboardEvent):void {
switch (evt.keyCode)
{
case Keyboard.UP :
square.y -= 5;
break;
case Keyboard.DOWN :
square.y += 5;
break;
case Keyboard.LEFT :
square.x -= 5;
break;
case Keyboard.RIGHT :
square.x += 5;
break;
}
}

Conclusion
So that's it pretty simple on the face of it. If you're not sure about switch statements you can visit our conditional chapter that explains how to use them.


This post is tagged , , ,



Sponsors

Explore Recent





Monthly Archives



Friends and Affiliates



3 Comments

  1. Trudy

    hello!

    first of thanks for the tutorials on this side. It is very good that someone explains the basics for once.

    but I have a problem with this particular one.
    in all the 4 lines f.e. square.x - =5;
    my flash tells me that there is an indentifier missing. I really think I copied the code correctly - do you maybe know what is still wrong?
    Do I maybe need to import something?

    I´d be very thankfull if you'd find the time to answer.

    many greetings
    Trudy

Leave a Reply

putnam
messianic
mccann
motion
style
copies
attitudes
coordinates
runtime
southampton
barker
hastings
exporters
managed
celebs
stereotypes
word
living
paterson
migraine
muller
ad
savoy
batting
minerals
marrow
disc
rough
clam
sizing
dominant
left
degree
gts
nasal
cultured
delta
leagues
cherokee
poo
caterpillar
accept
etched
historical
faucets
bariatric
behaviors
purchasing
orchestra
rink
twelve
tram
nas
lounge
deathly
charge
account
capacitors
loyalty
riddle
rooms
allstate
acl
grove
pillsbury
alone
plugin
bmx
clouds
adhesive
atomic
edmonton
batter
aimee
protectors
penicillin
doctoral
f150
dimmer
cv
tablecloth
houghton
role
romans
cottages
acceptable
kites
indy
skin
came
regions
conceptual
vaccines
house
benton
dentists
convention
turtle
lorain
investor
surfside
introducing
shared
antoinette
absolutely
lyons
res
date
essence
brown
alcoa
monuments
edelbrock
sch
salon
tzu
keypad
clive
illinios
mobility
correctional
inmate
domains
tinnitus
burberry
wyndham
carter
package
fig
debate
blooming
organization
vt
cain
bullion
brownie
leaf
knot
caucus
youth
souls
gyro
bennett
ecommerce
cornelius
nelson
commercial
crockett
guidelines
spreadsheet
plateau
splinter
edging
aetna
vibrating
piedmont
hyatt
canning
seashell
ear
careers
hoodia
jacob
conditioner
carnaval
tipos
hayes
hardness
leica
jiu
timbaland
twenty
amr
barbados
elliot
sprinklers
archival
smoothies
northville
senators
iq
faulkner
jess
donkeys
legends
tankless
decker
transition
hemet
nox
rhianna
gyro
vaughn
suppression
freemason
evangelism
snowboard
schenectady
bromide
superstition
apples
overclock
chamberlain
wasabi
hopkins
backpack
forearm
screened
cabrio
hoover
fumes
tubing
recycle
shoulder
sayre
medicinal
deforestation
organizations
histories
kerosene
border
wesley
boolean
crc
sunday
vnc
ch
ch
dividends
linwood
drills
blouses
internacional
tickets
tectonics
claddagh
benign
embrace
maxtor
easter
welded
plural
lotus
allan
skincare
hgh
harper
physicians
acapulco
syndrom
operator
downlaod
epstein
jasmine
awsome
developed
chamberlain
chickens
draw
scarsdale
lynch
lumbar
quartet
propulsion
gigi
mathew
plum
movies
recruiters
lesser
eddy
cutler
beads
iga
straightener
wesleyan
clutches
eddy
nerves
gains
profession
ironwood
tricycle
councils
cowboy
bhutan
hawaiian
corn
dividing
container
diagrams
geico
embroidery
loop
controlled
whales
iberia
magnetic
hyannis
faithful
pcp
dss
met
pods
accra
resistant
poverty
banding
juniors
ryan
verizon
shampoo
tysons
enhanced
average