admin管理员组文章数量:1394064
I know there's this keypress
even on Window
, which repeats if you hold the key, but it has this slight pause before the repetition starts. I don't want this pause. I'm writing a game where I want the player to react immediately, not after a pause.
What's the preferred way to handle keyboard events for web based games?
I know there's this keypress
even on Window
, which repeats if you hold the key, but it has this slight pause before the repetition starts. I don't want this pause. I'm writing a game where I want the player to react immediately, not after a pause.
What's the preferred way to handle keyboard events for web based games?
Share Improve this question asked Nov 25, 2012 at 15:58 TowerTower 103k131 gold badges364 silver badges521 bronze badges2 Answers
Reset to default 6Listen for "keydown", instead of "keypress". Keydown fires constantly until you let go.
BUT:
Do not just do something like:
window.addEventListener("keydown", function (evt) {
if (evt.keyCode === 32) { player.fire(); }
});
You'll end up with some people firing 15 times a second, and some people firing 60 times a second, and maybe even some firing 120 times per second.
Instead, have a Keyboard object which updates itself any time n event fires:
var Keyboard = {
keys : {},
keyPress : function (evt) {
if (this.keys[evt.keyCode] > 0) { return; }
this.keys[evt.keyCode] = evt.timeStamp || (new Date()).getTime();
},
keyRelease : function (evt) {
this.keys[evt.keyCode] = 0;
}
};
window.addEventListener("keydown", Keyboard.keyPress.bind(Keyboard));
window.addEventListener("keyup", Keyboard.keyRelease.bind(Keyboard));
Then, during your update cycle, have the character check the Keyboard
for the key it wants.
As an added bonus, they key has a timestamp of when it was first pressed, in case you want to add charge-up shots, or holding the button to jump higher.
Your units should then keep track of things like how often they're allowed to fire, and when the last time was, inside of their own update area.
Like Steve said, it's not possible. You should listen for the keydown / keyup events and keep track of what buttons are pressed:
var pressedKeys = {};
$(window)
.bind("keydown", function(e) {
pressedKeys[e.keyCode] = true;
})
.bind("keyup", function(e) {
delete pressedKeys[e.keyCode];
})
;
I think with games it's mon to have a main loop somewhere which handles all these events:
setInterval(function() {
if (pressedKeys[38]) { // if up is pressed
// do stuff
}
}, 50);
本文标签: htmlHow to listen to repetitive keyboard input without pauses on JavaScriptHTML5Stack Overflow
版权声明:本文标题:html - How to listen to repetitive keyboard input without pauses on JavaScriptHTML5? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744665254a2618490.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论