I have a Javascript key handler function and I'm trying to use it in a game that I'm working out but it doesn't seem to be quite working and I'm not sure if its the editor or the code has errors. My code is as shown:
var myKey = {
pressedKeys: [],
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
isPressed: function(zKey){
return this.pressedKeys[zKey];
},
onkeyDown: function(event){
this.pressedKeys[event.keyCode] = true;
},
onkeyUp: function(event){
this.pressedKeys[event.keyCode] = false;
},
};
window.addEventListener("keydown", myKey.onkeyDown);
window.addEventListener("keyup", myKey.onkeyUp);
var checkInput = function(){
if(myKey.pressedKeys[myKey.LEFT]){
confirm("Pressed Left");
}
}
var gameLoop = function(){
checkInput();
window.requestAnimationFrame(gameLoop);
}
The game loop animation frame is called the first time in a main function that's not shown here. I don't understand what could be going wrong. I tried hard coding numbers and still nothing but it could very well be my editor.
When you get a reference to a method and use that as an event handler, the function is no longer associated with the object.
thisinside the function is not a reference to themyKeyobject, but a reference to thewindowobject (as that is the object where the event happens).You can use the
bindmethod to specify the context for the functions:Note that the
bindmethod is not supported in some older browsers, for example IE8 and older, so you would need a 'polyfill' if you need to support them. There is one in the documentation that I linked to above.You can also use a function wrapper to call the methods: