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

consumer report on tankless water heaters best-free-movie-porn.com a mouses digestive system how to do needlepoint a needle pulling thread james johnstone joni belfast telegraph newspaper ecchi teacher ova antron compact electronic ballast blackout on a water ride jenniferanistonfakes.com 25 acres arizona christian fitness center smithfield ri uofm.com computer fixer arte contemporaneo excercises for torn rotator cuff sean hannity gun video mozart figaro 17 track moulin rouge cd adultclassified.com bed extenders chantal lemay realtor a separate peace envy capability study template bottle stopper favors caera kirsch marika vigo easylenderonline.com 2008 weight lifting accident andrews-products.com free synonym dictionary a robert paris clarinet ceo health investment decisions stargazersrealm.com a reason for handwriting kindergarten babystyle and entrepreneur magazine ana guerra oxnard birth date enya amino carcinoma egyptbeauty.com butler sweatshirt lake oconee shooting club after the lovin midi 1858 remington army revolver current prime intrest rate 3d cartoon index 1895 utah saddle makers 1 4 wall pipe load capacity jonathan sedgwick asus motherboard via chipset earthfaire.com 3dsmax landscape tutorial anders celsius life aon eligible rollover fund battery for dell inspiron 1150 hersheys kisses flower arrangement pakistanchristianpost.com andres vu strawberry 0.02 white cell count after chemotherapy lyrics thats not the airways tradera.com invisible braces orthodontic gresen minneapolis spool valve models 3240 lassen way sacramento ca charles v nickname addon wow search ancestorinfo.com j p sauer serial numbers alex jones interviews amy goodman 1 corinthians 14 33 a4 file manager air curtains fostoria crystal jefferson pattern picture bayer basket polymerizer berita keburukan program akademi fantasia clint eastwood and hillary oil of olay definity product review burnt creek club bismarck nd bestmedsmarket.com burnt hills wrestling tournament 1957 chevy convertible ra.com aboriginal veterans avalanche by arthur roth black and decker wallpaper steamer amy vs kanye 1900 sr maxum boat specs oregongolf.com slightly stoopid aug 4 young-lesbians.us cindy yates guiner lani all natural sausage 35 ah battery attractions in southwestern mn rodserling.com bard air alanon.org.za cannot ping default gateway 50 sodium hydroxide drifting events indiana mybb.ru john laurens hsbc michigan repossession notification law gotshemales.com miniclip m ussecurityassociates.com 1680x1050 images david crowder band tabs presentationexpert.com hurd family origin artists from marine-on-st croix mn accesso maestro beau de jour comevisit.com dj alex hidalgo mp3 shared files analyst notebook excel sanborn air compressors female gender representation in films audio mixing in the 1960s alabama state congressmen kcu.edu free outrageous funny weird photos bridgette elaine gaillot citi bank financial 4 seasons travel puerto rico berry athletic stadium cypress dungeons and dragons 3rd 1957 chevy alternator conversion desperate bad credit personal loan inter.co.yu accident steam cleaners inc alan charles clark said black and decker 4300 charity donate veterans thrift store phoenix blackberry muffins abba eurovision cheats for ratchet dead locked disable driver signing in vista x64 interior taj mahal auto fidelity finance bird buffer fabry-perot resonator celine cousteau flax and borage oil 1986 power ram w250 equator hidden fastener cath mersh gestational sac debris calphalon hard anodized cookware 1971 jimi hendrix passes bradley van ness mini-itx mainboard with hdmi abilene tourism amish 24 inch deacon bench nabe.org splinter blood clots antiphospholipid antibody syndrome north carolina nonresident shareholders identifying number lago como appartamenti vacanze inarng.org christmas in provence compounding pharmacies antarctica continent kids hospicebuffalo.com computadora en la educacion apple iphone news rumors blessed rosary andy warhol ceramic bronze bowl platypus bengals victoria c caribe ge products arecibo cheatcentral.com chaffoteaux maury barrows armour runescape armytents.com courtyard inn tuscaloosa 12-volt ceramic heater www-boxelderbugs.com calloway antique auction sanger texas extend brushes motor operationspringbreak.com abstracts on tea from plants 62 sanchez luis baby boomers the villages fl 19th century clothing reproductions dsp equalizer 1990 suzuki sierra lift kit bars irving texas burglar bars and alabama drkdesyre.com 5.0 hood guage pod air force parent weekend 1,4 dichloral benzene bamboo toothbrush allergy to coal mandarin chinese rowlett texas friendswood isd jobs 410 avenue school winnipeg healthierdogs.com brick oven in sparta tn 303 bullet trajectory brushed nickle fan light mnjobbank.com atv cullman barcelo bavaro santo domingo usedwinnipeg.com apartments in eau claire wi mako amps completed haccp plan training air chuck parkside at ashburn eplaymates.us britax boulevard in mosaic fixing lag on pc gaming amie dworecki cross functional decisions definition internetdatabases.com .22 rifle sales american woman heather graham build a bulkhead bangkok thai lacey wa bible marriage poems foe wedding couple 2000 election overseas vote zepka.com chronic ventricular fibrilation athens to rhodes flight eyewearmagic.com 1987 ferrari testarosa civil war colt revolvers antecedent behavior consequences expanded program immunization american trail riders association abingdon meat packers the fight over zac efron camp rock jonas brothers games california health care providers preferred choice chicken orange marmalade wild rice hon 3 drawer lateral file abc distributions company baton wall supports and studs cribbage score on paper showmeminitrucks.com augustus medlin jr section 202 wr ga abbott and costello bioraphy making popsicle stick dog sleds csmp.org ar-15 breakdown guide boy scout saves politician animated gifs for your email doi.org bill steele land art 3d tic tac toe instrucions john deere roto tiller hearst castle pictures decaf teas colombo baking co controled insanity burley knit terry 2007 updos hairstyles yokohama 235 60r16 avid trz 2.0 carat hearts on fire diamond importateurs chocolat belge cock-pictures.com modena agritourismus estimated cost attic insulation ga blackfoot idaho court house myimagefirst.com colourless deadly gas tarotburbrujas.com alexandria trips and tours planthaven.com detroit hiphop r b artists stepsforpets.com basketball blankets comforters quilts 07e7 listing all things organic conference chinook campground hernandomls.com aerosoles sunbeam sandal biblestoriesforadults.com earth magnitude northridge quake naughtyamateurcinema.com artificial reef coral decorative boundaries divorce relationships and jealousy agence de positionnement blueridgeimpressions.net compaq monitor presario mv700 user guide j renee lorraine jocelyn goldring woldenberg hall tulane southpark 2008 13 the movie free on line stargate gaming azo dye prohibition samuel paul thierry bmw m5 twinscrew supercharged kit invision power board ipb button 5 gallon mini bow ann fagelson government seminars christmas cactus blossoms nvisible.com 3d apple themes calm hyper dog havoc boxing discount expresso machines beanstreamcarts.com 2004 tacoma factory alarm cap tel telephones hard of hearing advest boca raton fl 2001 cost of living cortisone knee shots 1stophomebuyer.com brian levine carolina access enrollment form medicaid healthcare tenders dai vernon signed buy short-on-cash.com dr john lee benin azalea middle school norfolk va amy macdonald poison prince reviews komkon.org classical guitarist 12-15 girl photos john atchison child solicitation ac power adapter to cigarette lighter 13th anniversary show business card upload jacobsen architect giftscandle.com bean bag lap desk with light cibc banks toronto 3-d wooden sign 503 n oakland carbondale average daily temperatures new york melissa ursula dawn goldsmith november 2006 ubs aluminum foil dissolution with ferrous sulfate crack wall sidewalk drawing or picture imer.com.mx aiken hearing impaired cameron tract parsippany 1985 toyota tercel wagon lean on me bill withers lyrics what is hyaluronic acid collaborative change chiropractic subacromial bursitis classmate locater