You need to add an event listener to track the key event. In the below example I used keyup
as this will run once the key has been released.
In the callback function of the event listener you will be given an event
object and from this object you can check something called a keyCode
(or in older browsers which
). Each key on the keyboard has a mapped number to it so you can trace back to whether a D
, W
, A
, or S
was passed for instance and call different methods based on that.
I've written some generic object oriented code below to show how this could be achieved. See how the event is passed from addEventListener
callback to keyPressed
, and keyPressed
runs the logic for moveRight
if the code matches 68
.
function GameName() {
// ... constructor stuff ...
// add keypressed method on keyup
document.addEventListener('keyup', function(event) {
this.keyPressed(event);
}.bind(this));
}
GameName.prototype.keyPressed = function(event) {
// browser compatibility check for event and event code
var e = event || window.event,
code = e.which || e.keyCode;
// If user pressed 'D' key (google for javascript key codes)
if (code === 68) {
this.moveRight();
}
}
GameName.prototype.moveRight = function(event) {
// user moves right
}