Stick Page Forums Archive

AS3 KeyListeners/Focus

Started by: Steyene | Replies: 2 | Views: 733

Steyene

Posts: 2,060
Joined: Apr 2006
Rep: 10

View Profile
Nov 15, 2008 7:56 AM #294600
Okay, I am slowly learning AS3. So I thought that I would start off with a basic movement script (WASD). So I set up a text box to show the codes, as it is AS3 considers upper and lower cases as different keys. Anyway, I export it and then press WASD, nothing happens, so I click the text box and then magically it works. Anyway

My Script:
var stagex:Number = 550;
var stagey:Number = 400;
stage.focus = stage;
addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
//Listeners
var key:Number;

//variables

function onKeyDown(event:KeyboardEvent):void{
key = event.charCode;
ascii_box.text = "Key down:"+key;
if(key == 97){
this.player.x -=5;
}
if(key == 100){
this.player.x += 5;
}
if(key == 119){
this.player.y -= 5;
}
if(key == 115){
this.player.y += 5;
}
}


The swf with the text box.

The swf without the text box

Both codes are the same except for the one without the text box has
ascii_box.text = "Key down:"+key;
remed out.

Halp Please
darkcampainger
2

Posts: 159
Joined: Aug 2006
Rep: 10

View Profile
Nov 15, 2008 5:20 PM #294932
Change "addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);" to "stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);"

Also, you shouldn't use "onKeyDown" as a function name, since it was reserved in AS2 and causes the AS3 compiler to think you're using AS2 :P

Most people use onKeyPress and onKeyRelease, but you can use just about anything.


Also, you might want to read this for smoother keyboard input handling:
http://www.kirupa.com/forum/showthread.php?p=2098269#post2098269
Steyene

Posts: 2,060
Joined: Apr 2006
Rep: 10

View Profile
Nov 15, 2008 9:45 PM #295067
Okay, I will try that. Thanks

Edit: Yup it works.
Website Version: 1.0.4
© 2025 Max Games. All rights reserved.