Flash Essential

AS3 Guide Keyboard Events

Sep 15th 2008
4 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



4 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

  2. Tara

    How can I make work by clicking at the keyboard without clicking at the the square first?

    Thank you,

    Tara

Leave a Reply

  • acupressure for fertility
  • 1989 calander
  • 218 bee rifle
  • african opal pendant
  • san vito lake garda
  • domain masking
  • akron childrens hospital akron ohio
  • actors digs leicester
  • african origin
  • plainfield quakers
  • safetybath.com
  • future state processes included review
  • cathy ann taylor sausalito
  • theperfectcowgirl.com
  • chakra days
  • kittens.com
  • oreo bars
  • emuonline.edu
  • always portraits by sally
  • buy exxon mobile gift card
  • australias most economical cars
  • pennslyvania snakes
  • amo ontario
  • 12 volt circuit diagram
  • boney shoulders
  • christian jules leblanc
  • college football announcer
  • fontaine scarlett
  • 70 easton ave
  • current time in ramstein germany
  • 1-ads.net
  • arch benson iowa
  • beaked whale molokai
  • edneyco.com
  • porsche targa
  • 2009 phase-out ranges and contribution limits
  • checkbookcovers.com
  • bugatti replicas
  • iss blackice
  • callaway ft5 fade driver
  • anne hathaway see through
  • 1990 nissan skyline gtr fuel consumption
  • ageless wisdom university template
  • amarte asi online video
  • 1981 leisure arts cross stitch
  • christian dior gown
  • zambiatourism.com
  • 2500 4x4 traction bars
  • 1963 250 sl
  • xxxsurprise.com
  • bob schmidt amway
  • robin williams scotsman golf
  • advantages and disadvantages of plea bargaining
  • ballet easel
  • 26 southgate avenue southbank
  • alicia silverstone youtube
  • ces free pass 2009
  • chaos firefly
  • aggresive inline ps2
  • holly slade north providence
  • evergreen.ca
  • ed helms oot of the closet
  • lost canyons golf
  • babylon 5 forums and chat rooms
  • continuum of health care
  • westlandmall.net
  • free baby stiff
  • tokyopop.co.uk
  • ergonomic chair parts
  • adoption records buenos aires
  • delivery status notification sandie notification generated
  • 1900 golf equipment
  • ev battery charger
  • chicagotech.net
  • av jennings maidstone
  • harley davidson lehman trike
  • gunz the duel hack
  • furniture sledge bed
  • article about attitude
  • clothes made from soybean ffabric
  • blackpowder squirrels
  • english capitalization worksheets
  • does the gym stunt growth
  • casio advertisments g shock
  • 2.4 ghz cordless phone battery
  • bumper sticker driver may sing
  • 3m reflective lettering star of life
  • abingdon bio-renewable fuels
  • adel jarvis guitar
  • venezuelan
  • cavendish lettings
  • trictrenchless.com
  • bobbie graves supply co
  • caribbeanworldnews.com
  • 97 ford explorer ball joints
  • 24 math game solutions and hints
  • boxing excercises
  • alton betty hutchinson
  • 40 29 school closing
  • pitbullsuccess.com
  • emphysema prognosis
  • greeces landforms
  • bayer advocate
  • grossmont.net
  • after eating allergy attack
  • density gas mixture
  • plate tectonics evidence
  • all chemicals in cigarette
  • dominion hotel kamloops b c
  • 1983 country squire
  • 2007 2008 health technology assessment
  • 138 sonnet
  • deni sealers review
  • pumpkin festival romulus michigan
  • foodclipart.com
  • 118 directory iran whitepage
  • remembering babylon summary
  • classification on race and ethnicity
  • baby congratulations quote
  • adelaide australian shepherds
  • horse boarder johns island sc
  • 2008 democratic conventiion
  • wgts.org
  • joy moulton
  • come thou almighty king alternate words
  • ayia napa easter breaks
  • canon pc720 error code e2
  • american-indian-art.com
  • acdc razor edge
  • 4 cylinder vehicles
  • fast and furious 3
  • doctorate in naturopathic medicine online
  • deciduous forest interesting facts
  • basketba pendants
  • aj drew
  • grivel rambo 3 crampons
  • 366 trs det 6
  • gonzaga mens basketball tickets
  • momtana silversmith barettes
  • capel sewell nj
  • illuminati and mayan
  • business seekers
  • ddstarlets.com
  • edict nantes 1598
  • bavarian chalet estes park co
  • clark frasier mark gaier
  • automatically insert lyrics into ipod
  • fixpcerrors123.com
  • elearning authoring tools
  • 5 16 allen bolts
  • eighteen lyrics alice cooper
  • halfway homes tampa
  • challenges in implementing web-based systems
  • how do planarians reproduce
  • assisted living kerrville texas
  • fleet rents
  • datingandchat.com
  • bates method vision correction
  • nafta trademarks
  • omer camo wetsuit
  • adrian leonard thomas
  • articles on building employee morale
  • groovy girl kendra
  • 300 ex racing quads for sale
  • surefire foregrip light
  • northstar resort truckee ca
  • 1983 drag racing
  • business and travel expense policy sample
  • adam mann and drummer
  • jai leighton
  • goodwill ambulance
  • choking cough nz
  • archie ferguson glasgow
  • is maurice clay marianna florida married
  • chatroom html
  • coffee shoppe frontpage templates
  • 4wheel parts wholesalers transamerica
  • interpersonal dynamics in a simulated prison
  • 197 sport pioneer boat
  • eldon colquit holt obit ga 1999
  • 14 digit pins
  • 1 mil trace pcb design
  • ancestry germany
  • good-porns.com
  • 1-01 main theme overworld
  • business magazine article managing burger flippers
  • peking delight laurel md
  • nuke attack noble resolve
  • athearn husky
  • bmc pumping western nc
  • michigan wolverine on radio
  • adhesive curing qk 50 splash unfiltered
  • 1930 magic chef stove
  • dirt thrasher tamiya
  • obra social fundacion la caixa pintada
  • blue saw palmetto
  • amber stevens tn
  • caracteristicas de los seres vivos
  • boyshadow.com
  • amazon com tomb raider video games
  • cheats for evil genius on laptop
  • cartagena finca raiz
  • carpenters toolbox homemade
  • emergency department outcomes
  • door-knobs-etc.com
  • collin w fritz
  • $1000 jeans
  • sirc.org
  • aerating and sanding zoysia lawns
  • drawer freezers
  • 20 oz plastic tumbler
  • caregiver belleville
  • putty server refused to open
  • alugar casa portugal lagos
  • ipod nana covers
  • glensold.com
  • bastide roger de leyburn
  • eugene huang sandusky oh
  • bestxxxmedia.com
  • allied princess 36
  • hemorrhoid diet
  • arlo guthrie lryics
  • gastro and stools
  • academy school district twenty
  • black lab silhouette clipart
  • 2006 prowler campers
  • air gear manga scans
  • olympic oxy deck
  • april stein
  • asbury park apartment homes kirkland
  • kalispell realistate
  • 3 season rooms new hampshire
  • build swim raft
  • ckswebhost.com
  • 1983 diane keaton
  • 17th president of the u s
  • 1941 brooklyn dodgers photos
  • avant guards
  • nastybbwmama.com
  • asme definitions
  • bigfoot canoes
  • patskingofsteaks.com
  • anti-aging supplements tocotrienols
  • curtsrodandcustom.com
  • no sooner longings fade
  • 2 blade vs 3 blade propeller
  • anti caking agent for fertilizers
  • howard johnsons hotels in windsor conn
  • selfworkoutintheparkcheckout.com