I am creating a simple game with functions to move a player forward,turn left,turn right, or turn around. I want the key presses to fire the specific corresponding function only once. I found this helpful code that fires the event only once, but I cannot seem to figure out how to specify certain key presses within it.
var shouldHandleKeyDown = true;
document.onkeydown = function(){
if (!shouldHandleKeyDown) return;
shouldHandleKeyDown = false;
// HANDLE KEY DOWN HERE
}
document.onkeyup = function(){
shouldHandleKeyDown = true;
}
})();
What I am trying to make happen is:
User presses up? Move forward function occurs ONCE (even if the up key is held)
User presses left? Turn left function occurs once etc....
Thank you all for any help with this.
EDIT FOR CLARIFICATION:
I am trying to build a first-person dungeon crawler in the style of old titles like Wizardry for the NES. Basically I want each press of the forward button to move the player forward one frame. If they press left then the player turns left one frame, etc. If you are familiar with the games you will get what I mean.
I would ignore onkeydown events and just use onkeyup. That way the event is only fired once the user lifts their finger, ensuring just one movement per key press.
To determine which key was pressed inside your event handler, pass the event to your function. Here is a link to the values of the keys, so you could do something like:
document.onkeyup = function(event) {
var keycode = event.keyCode;
if (keycode === 38) {
moveUp();
}
}