简体   繁体   中英

Determining if key is pressed down in Javascript

I'm writing a platform game for my university project using the canvas element and Javascript. I'm well on my way, but I'm stuck at how to see if a certain key is being pressed in my players update loop.

I was thinking like this:

if(d) {
    // move player right
} else if(a) {
    // move player left
} else if(w) {
    // move player up
} else if(s) {
    // move player down
}

That's psudocode, obviously. The only resources to key presses in Javascript that I can find are events, nothing to see if a key is being pressed at a certain point.

Can anyone shed some light on this?

Setup 4 boolean variables if key is up or down. On keydown set it to true, on keyup set it to false. Than you can do if(key_d == true) { // key d is pressed }

That's the best way to do it. Its not "hacky", add event listeners to handle key presses.

I don't think you can get around using keydown , keyup , or keypress for determining which keys are pressed. However, instead of running this code within one of those event handlers, you could set and unset some global flag within them. Then, when this code runs (I'm assuming it'll be on some kind of interval?), it could check for the flag.

You need an event listener.

//function foo, returns keypress
function foo(e){
var evt=(e)?e:(window.event)?window.event:null;
if(evt){
    var key=(evt.charCode)?evt.charCode:
        ((evt.keyCode)?evt.keyCode:((evt.which)?evt.which:0));
    return key;
}

//set event listener
//you could also attach this to your canvas, but that will require tricks
//to make the canvas focusable
document.addEventListener('keydown', foo);  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM