Reputation: 32374
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.
Upvotes: 0
Views: 615
Reputation: 8588
In firefox you need to use e.which
instead of e.keyCode
.
You can make it compatible with:
var keyCode = e.which || w.keyCode;
Upvotes: -1
Reputation: 349232
The non-standard window.event
object is only available in IE and Chrome.
In standard-compliant browsers, the event
object is passed as a first argument to the event listener.
Change:
function press() {
if (!ni) {
var evt=window.event;
to:
function press(evt) { // <-- Declaration of evt
if (!ni) {
evt = evt || window.event; // <-- Notice: var is omitted
Equivalently:
function release(evt) {
Upvotes: 3