Created
April 11, 2012 04:46
-
-
Save mrcoles/2356963 to your computer and use it in GitHub Desktop.
A simple way to keep track of which keys are pressed at any one time.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var PressedKeys = function($elt) { | |
var pressed = {}; | |
($elt || $(document)).on('keydown keyup', function(evt) { | |
pressed[evt.keyCode] = (evt.type == 'keydown'); | |
}); | |
return pressed; | |
}; | |
// example | |
var pressedKeys = PressedKeys($('canvas.game')); | |
(function loop() { | |
if (pressedKeys['39']) { | |
// do something right | |
} else if (pressedKeys['37'] { | |
// do something left | |
} | |
window.setTimeout(loop, 80); | |
})(); |
why not gist.
done.
“gist do it!”
@mrcoles Hello from 2024.
typo here:
} else if (pressedKeys['37'] {
should be:
} else if (pressedKeys['37']) {
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why not just:
pressed[evt.keyCode] = (evt.type == 'keydown');