Actionscript:
-
var key:Object = new Object();
-
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
-
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
-
function onKeyPressed(evt:KeyboardEvent):void {
-
key[evt.keyCode] = true;
-
key.keyCode = evt.keyCode;
-
}
-
function onKeyReleased(evt:KeyboardEvent):void {
-
key[evt.keyCode] = false
-
}
-
-
// example
-
-
addEventListener(Event.ENTER_FRAME, onLoop);
-
function onLoop(evt:Event):void {
-
-
//trace(key.keyCode);
-
-
if (key[Keyboard.LEFT]){
-
trace("left");
-
}
-
-
if (key[Keyboard.RIGHT]){
-
trace("right");
-
}
-
-
// keys #1, #2 and #3 are down
-
if (key[49] && key[50] && key[51]){
-
trace("one two thee");
-
}
-
-
// keys #6, #7, #8 and #9 keys are down
-
if (key[54] && key[55] && key[56] && key[57]){
-
trace("six seven eight nine");
-
}
-
}
The first 10 lines of code make up this snippet. This is an easy way to keep track of multiple key presses. For games, this is the only key technique I use ... wrapped up in a Singleton.
4 Comments
hi,
my doubt is that when multiple keys have been pressed like on line 28 and 33,
how do i make my clip move diagonally…
say when i press the left and up key my clip should move diagonally left up….
vibil… well…. this snippet works nicely for that… try this code:
var character:Shape = Shape(addChild(new Shape()));
with(character.graphics) beginFill(0×000000), drawCircle(0,0,10);
character.x = character.y = 100;
var key:Object = new Object();
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyReleased);
function onKeyPressed(evt:KeyboardEvent):void {
key[evt.keyCode] = true;
key.keyCode = evt.keyCode;
}
function onKeyReleased(evt:KeyboardEvent):void {
key[evt.keyCode] = false
}
// example
addEventListener(Event.ENTER_FRAME, onLoop);
function onLoop(evt:Event):void {
//trace(key.keyCode);
if (key[Keyboard.LEFT]){
character.x -= 4;
}
if (key[Keyboard.RIGHT]){
character.x += 4;
}
if (key[Keyboard.UP]){
character.y -= 4;
}
if (key[Keyboard.DOWN]){
character.y += 4;
}
}
Hey thanx very much.