File: keyboard-input\System.js
/**
This system is reponsible for translating key presses into actions for entities that have the Input component. This system checks which keys are pressed and for each entity, if that key press translates into an action, it sends an event with that action as the name and the entity as the argument.
@class KeyboardInputSystem
@constructor
@param entitySystemManager {Manager} The entity system manager whose entities this system will be working on.
@extends EventHandler
*/
function KeyboardInputSystem(entitySystemManager){
//Inherit from the event handling object.
EventHandler.call(this);
var thisKeyboardInputSystem = this;
//=====Keyboard key flags=====
var keyFlags = new Array(223);
//Every flag is false by default.
for(var i=0; i<keyFlags.length; ++i){
keyFlags[i] = false;
}
function keyDown(event){
var keyCode = event.which || event.keyCode;
keyFlags[keyCode] = true;
}
function keyUp(event){
var keyCode = event.which || event.keyCode;
keyFlags[keyCode] = false;
}
document.addEventListener('keydown', keyDown);
document.addEventListener('keyup', keyUp);
//=====Input handling=====
var entities = entitySystemManager.createAspect([KeyboardInput]),
handleInput = true;
/**
Disables input handling for all entities.
@method disable
*/
this.disable = function(){
handleInput = false;
};
/**
Enables input handling for all entities.
@method enable
*/
this.enable = function(){
handleInput = true;
};
function sendInputEvents(entity){
var keyBindings = entity.get(KeyboardInput)._keyBindings,
action;
for(var i=0; i<keyFlags.length; ++i){
//If the given key is pressed,
if(keyFlags[i]){
//check if there's a corresponding action in this entity's key bindings.
action = keyBindings[i.toString()];
if(action){
//If there is an action bound to this key, trigger an event for it.
thisKeyboardInputSystem.trigger(action, entity);
}
}
}
}
/**
@method update
*/
this.update = function(){
if(handleInput){
entities.iterate(sendInputEvents);
}
};
/**
@method destroy
*/
this.destroy = function(){
document.removeEventListener('keydown', keyDown);
document.removeEventListener('keyup', keyUp);
entities.destroy();
};
}
//Inherit from the event handling object.
KeyboardInputSystem.prototype = Object.create(EventHandler.prototype);
KeyboardInputSystem.prototype.constructor = KeyboardInputSystem;