flash - Can I track the keys pressed, using ActionScript? -


can track keys pressed, using actionscript?

i use class made while back:

edit: cleaner now.

    package     {         import flash.display.stage;         import flash.events.keyboardevent;          public class keys extends object         {             // vars             private var _keys:array = [];              /**              * constrcutor              * @param stg stage apply listeners              */             public function keys(stg:stage)             {                 stg.addeventlistener(keyboardevent.key_down, _keydown);                 stg.addeventlistener(keyboardevent.key_up, _keyup);             }              /**              * called on dispatch of keyboardevent.key_down              */             private function _keydown(e:keyboardevent):void             {                 //trace(e.keycode);                 _keys[e.keycode] = true;             }              /**              * called on dispatch of keyboardevent.key_up              */             private function _keyup(e:keyboardevent):void             {                 delete _keys[e.keycode];             }              /**              * returns boolean value represents given key being held down or not              * @param ascii ascii value of key check              */             public function isdown(...ascii):boolean             {                 var i:uint;                 each(i in ascii)                 {                     if(_keys[i]) return true;                 }                  return false;             }         }     } 

it's simple here: create instance of keys , use isdown() method.

    var keys:keys = new keys(stage);      addeventlistener(event.enter_frame, _handle);     function _handle(e:event):void     {          if(keys.isdown(65)) trace('key held down');     } 

it can check multiple keys @ once:

if(keys.isdown(65, 66)) // true if 'a' or 'b' held down. 

edit:

it helps lot when you're testing using compile (ctrl+enter) disable keyboard shortcuts (control -> disable keyboard shortcuts).


Comments