I found a script that can handle input for a small HTML5 based game I’m building:
var KEY = {W: 87, A: 65, S:83, D: 68, E: 69};
var input = {
right: false,
up: false,
left: false,
down: false,
e: false
};
function press()
{
if (!ni)
{
var evt=window.event;
var code = evt.keyCode;
switch(code)
{
case KEY.W: input.up = true; break;
case KEY.A: input.left = true; break;
case KEY.S: input.down = true; break;
case KEY.D: input.right = true; break;
case KEY.E: input.e = true; break;
}
}
}
function release()
{
if (!ni)
{
evt=window.event;
var code = evt.keyCode;
input.code = code;
switch(code)
{
case KEY.W: input.up = false; break;
case KEY.A: input.left = false; break;
case KEY.S: input.down = false; break;
case KEY.D: input.right = false; break;
case KEY.E: input.e = false; break;
}
}
}
This is how the event handlers are assigned:
document.addEventListener("keydown", press);
document.addEventListener("keyup", release);
The variable ni that shows up occasionally is true when the player is entering text in a text box, I’m pretty sure that it isn’t causing the problems. Also, this works perfectly in chrome, but as I said, doesn’t work in Firefox. Anybody care to explain why? Firefox version: 10.0.2.4428.
The non-standard
window.eventobject is only available in IE and Chrome.In standard-compliant browsers, the
eventobject is passed as a first argument to the event listener.Change:
to:
Equivalently: