Reputation: 539
I am trying to make a game which has the feature that if you hold the shift key, the player will speed up. I tried to use keyEvent but it can't detect the key is held or pressed. and when I release the shift key, the player remains in speed up mode and won't change the speed back to normal. is there any possible way to achieve this?
Upvotes: 0
Views: 152
Reputation: 16384
You should listen for two events: keydown
and keyup
. In every event type you should check for key (the keycode of "shift" is 16), and on keydown
you should start an action, and on keyup
stop it (if event.keyCode === 16
). Here is a simple example with text color, it becomes red while "shift" is pressed (don't forget to click on opened window of the snippet, it will not work without it because without focusing on this window all events will be "out of scope" for the snippet):
var onkeydown = (function (e) {
if (e.keyCode === 16) {
document.getElementById("target").style.color = "red";
}
});
var onkeyup = (function (e) {
if (e.keyCode === 16) {
document.getElementById("target").style.color = "black";
}
});
<h1 id="target">Red when holds "shift"</h1>
Upvotes: 3