Can I track the keys pressed, using ActionScript?
Can I track the keys pre开发者_如何学Pythonssed, using ActionScript?
I use this class that I made a while back:
EDIT: Slightly cleaner now.
package
{
import flash.display.Stage;
import flash.events.KeyboardEvent;
public class Keys extends Object
{
// vars
private var _keys:Array = [];
/**
* Constrcutor
* @param stg The stage to apply listeners to
*/
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 a boolean value that represents a given key being held down or not
* @param ascii The ASCII value of the key to check for
*/
public function isDown(...ascii):Boolean
{
var i:uint;
for each(i in ascii)
{
if(_keys[i]) return true;
}
return false;
}
}
}
It's simple from here: create an instance of keys and use the isDown() method.
var keys:Keys = new Keys(stage);
addEventListener(Event.ENTER_FRAME, _handle);
function _handle(e:Event):void
{
if(keys.isDown(65)) trace('key A is held down');
}
It can even check for multiple keys at once:
if(keys.isDown(65, 66)) // true if 'a' or 'b' are held down.
EDIT:
It also helps a lot when you're testing using compile (ctrl+enter) to disable keyboard shortcuts (control -> disable keyboard shortcuts).
精彩评论