I have made a class to import into my projects to more easily handle the state of the keyboard so I can use stuff like:
if(Keys.returnKey(37)){
As opposed to setting up key listeners.
Please give this code a general review:
/*
ALWAYS DO THIS FIRST:
Keys.init(stage);
THEN YOU CAN DO THESE:
Keys.returnKey(5);
Keys.returnArray(37,38,39,40);
Keys.returnLastKeyPressed(37,38,39,40);
*/
package{
import flash.events.KeyboardEvent;
import flash.display.DisplayObjectContainer;
public class Keys{
private static var _key_arr:Array=[];
// Contains boolean values for each keycode
private static var _last_key:int=0;
// Last key pressed
private static var _last_valid_key:int=0;
// Last valid key pressed
// PUBLIC FUNCTIONS:
public static function init(STAGE:DisplayObjectContainer){
// Prepares class for use, call this once before you start using the other functions
for (var i=0; i<222; i++){
_key_arr[_key_arr.length]=false;
}
STAGE.addEventListener(KeyboardEvent.KEY_DOWN, keyD);
STAGE.addEventListener(KeyboardEvent.KEY_UP, keyU);
}
public static function returnKey(INDEX:int):Boolean{
// Returns a single value from _key_arr at the index of INDEX
return _key_arr[INDEX]
}
public static function returnArray(... args):Array{
// Returns values from _key_arr to the locations passed as the parameter(s)
var returnMe:Array=[]
for (var i=0; i<args.length; i++){
returnMe[i]=_key_arr[args[i]];
//Extracts the values of the keys passed in as args from the key array.
}
return returnMe;
}
public static function returnLastKeyPressed(... args):int{
// Returns the keyCode of the key most recently depressed
if(args.indexOf(_last_key)!=-1){
_last_valid_key=_last_key;
}
return _last_valid_key
}
// PRIVATE FUNCTIONS:
private static function keyD(event:KeyboardEvent){
// Sets the pressed key's value to true and sets the last key pressed
_key_arr[event.keyCode]=true;
_last_key=event.keyCode;
}
private static function keyU(event:KeyboardEvent){
// Sets the pressed key's value to false
_key_arr[event.keyCode]=false;
}
}
}