1

So I'm making a game and I want to be able to add controls for a character. So I want the game to be able to detect if the user presses the key W. Something like this

    if(W is pressed){
     Do something
    }

4 Answers4

1

The following code should do it for you

function keyW(e) {
    if(e.keyCode === 87){
       console.log('w');
    };
}
document.onkeydown = keyW;
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54
1

You can add an EventListener for keydown and check the event :

document.addEventListener('keydown', function(e){
   if(e.key === 'w')
   console.log('hei w')
})
maioman
  • 18,154
  • 4
  • 36
  • 42
1

If you already capture the keypress, you can just convert the event key number to a character and then proceed with your condition as following:

if ( String.fromCharCode(keynum) == 'W' ) {
    // Processing
}

If you're not capturing the event yet, just do as following:

document.onkeypress = function(e) {
    var keynum = e.which;
    if ( String.fromCharCode(keynum) == 'W' ) {
        // Processing
    }
};
anatoli
  • 336
  • 6
  • 14
-1

You can use onkeypress event for this.

The onkeypress event occurs when the user presses a key (on the keyboard).

In HTML:

<element onkeypress="myScript">

In JavaScript:

object.onkeypress=function(){myScript};

In JavaScript, using the addEventListener() method:

object.addEventListener("keypress", myScript);

I took this information from http://www.w3schools.com/jsref/event_onkeypress.asp You can also search internet for more information about events in javascript language. Good Luck!