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
}
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
}
The following code should do it for you
function keyW(e) {
if(e.keyCode === 87){
console.log('w');
};
}
document.onkeydown = keyW;
You can add an EventListener for keydown
and check the event
:
document.addEventListener('keydown', function(e){
if(e.key === 'w')
console.log('hei w')
})
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
}
};
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!