PDA

View Full Version : Keyboard event


onotole
09-13-2009, 07:16 PM
Hi everyone, I've got a problem, when I am pressing a key nothing happens. If you got any idea about why it is, please tell me. Thanks.

I have 2 AS files and a Ship object in the library.
1st is Engine.

package {
import flash.display.MovieClip;

public class Engine extends MovieClip {
private var ourShip:Ship=new Ship();

public function Engine() {
addChild(ourShip);
}
}
}

2nd is Ship

package {
import flash.display.MovieClip;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;

public class Ship extends MovieClip {

public function Ship() {
addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
}

private function keyPressed(e:KeyboardEvent):void {
//left or A
if (e.keyCode==37||e.keyCode==65)
x-=2;
//right or D
else if (e.keyCode==39||e.keyCode==68)
x+=2;
//down or S
if (e.keyCode==40||e.keyCode==83)
y+=2;
//up or W
else if (e.keyCode==38||e.keyCode==87 )
y-=2;
}
}
}

hauni
09-13-2009, 08:56 PM
Try adding this instead:

package {
import flash.display.MovieClip;
import flash.ui.Keyboard;
import flash.events.KeyboardEvent;

public class Ship extends MovieClip {

public function Ship() {
addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
}

private function keyPressed(e:KeyboardEvent):void {
//left or A
if (e.keyCode==37||e.keyCode==65)
ourShip.x-=2;
//right or D
else if (e.keyCode==39||e.keyCode==68)
ourShip.x+=2;
//down or S
if (e.keyCode==40||e.keyCode==83)
ourShip.y+=2;
//up or W
else if (e.keyCode==38||e.keyCode==87 )
ourShip.y-=2;
}
}
}

Mazoonist
09-13-2009, 09:18 PM
If you are testing in the Flash IDE, you have to pull down the Control menu on the running SWF (not Flash itself) and choose "Disable keyboard shortcuts." Otherwise, some keys and key combinations are intercepted by flash itself. For example, pressing "P" chooses the Pen tool, even when your swf is running. If you've programmed the P key to do something, it will seem to not work, because flash is stealing that keystroke. That's why the "Disable keyboard shortcuts" command exists, so that you can turn this "feature" off.