events - Javascript Key Handler -
i have javascript key handler function , im trying use in game im working out doesnt seem quite working , im not sure if editor or code has errors. code 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 called first time in main function thats not shown here. dont understand going wrong. tried hard coding numbers , still nothing editor.
when reference method , use event handler, function no longer associated object. this
inside function not reference mykey
object, reference window
object (as object event happens).
you can use bind
method specify context functions:
window.addeventlistener("keydown", mykey.onkeydown.bind(mykey)); window.addeventlistener("keyup", mykey.onkeyup.bind(mykey));
note bind
method not supported in older browsers, example ie8 , older, need 'polyfill' if need support them. there 1 in documentation linked above.
you can use function wrapper call methods:
window.addeventlistener("keydown", function(e){ mykey.onkeydown(e); }); window.addeventlistener("keyup", function(e){ mykey.onkeyup(e); });
Comments
Post a Comment