l0ckw00d l0ckw00d - 2 months ago 18
Javascript Question

javascript eventlistener not working

I want to make a startscreen with the function to start the game when the user presses SPACE but my code doesn't work.

var level1 = false
var keys = [];

window.addEventListener("keydown", function(e){
keys[e.keyCode] = true;
}, false)

window.addEventListener("keyup", function(e){
delete keys[e.keyCode];
}, false)

context.font = "bold 35px Arial";
context.fillText("Press Space to Start", 290,300);

if(keys[32]){
level1 = true;
}


but when i press SPACE the variable level1 is still on false. I've checked it with the google chrome console.

Answer

but when i press SPACE the variable level1 is still on false

Yes. Why would it be anything else? Nothing in your event handlers is updating it.

If you want to update it when an event occurs, update it in the event handler.

Perhaps have a function that updates the state of any variables you want tracking key state and call it from both event handlers:

var level1 = false
var keys = [];

window.addEventListener("keydown", function(e) {
    keys[e.keyCode] = true;
    checkKeyState();
}, false)

window.addEventListener("keyup", function(e) {
    delete keys[e.keyCode];
    checkKeyState();
}, false)

context.font = "bold 35px Arial";
context.fillText("Press Space to Start", 290, 300);

function checkKeyState() {
    if (keys[32]) {
        level1 = true;
    } else {
        level1 = false;
    }
}

Note that checkKeyState can also be written:

function checkKeyState() {
    level1 = !!keys[32];
}

...but I didn't want to throw that at you in the first code block.