var EHDI = EHDI || Object.create(null); EHDI.interactions = EHDI.interactions || Object.create(null); EHDI.interactions.Keyboard = function (keyCode) { var key = {}; key.code = keyCode; key.isDown = false; key.isUp = true; key.press = null; key.release = null; key.downHandler = function(event) { if(event.keyCode === key.code) { if (key.isUp && key.press) key.press(); key.isDown = true; key.isUp = false; } }; key.upHandler = function(event) { if(event.keyCode === key.code) { if(key.isDown && key.release) key.release(); key.isUp = true; key.isDown = false; } }; var downHandle = key.downHandler.bind(key), upHandle = key.upHandler.bind(key); window.addEventListener("keydown", downHandle, false); window.addEventListener("keyup", upHandle, false); key.dispose = function() { window.removeEventListener("keydown", downHandle); window.removeEventListener("keyup", upHandle); } return key; } EHDI.interactions.ArrowControl = function (sprite, speed) { if(typeof speed === undefined) throw new Error("Indicate speed in which you whant the sprite to move"); var upArrow = EHDI.interactions.Keyboard(38), rightArrow = EHDI.interactions.Keyboard(39), downArrow = EHDI.interactions.Keyboard(40), leftArrow = EHDI.interactions.Keyboard(37); leftArrow.press = function() { sprite.vx = -speed; } leftArrow.release = function() { if(!rightArrow.isDown) sprite.vx = 0; } rightArrow.press = function() { sprite.vx = speed; } rightArrow.release = function() { if(!leftArrow.isDown) sprite.vx = 0; } upArrow.press = function() { sprite.vy = -speed; } upArrow.release = function() { if(!downArrow.isDown) sprite.vy = 0; } downArrow.press = function() { sprite.vy = speed; } downArrow.release = function() { if(!upArrow.isDown) sprite.vy = 0; } };