I am currently developing a webGL game with the Three.js library that involves movement in space using keyboard arrows. I am working on allowing users to simultaneously move and rotate by pressing the left-right arrow keys together with the up-down arrow keys. To achieve this, I have created a key map that keeps track of the status of all necessary keys. Here is the code snippet:
var keyMap = [];
document.addEventListener("keydown", onDocumentKeyDown, true);
document.addEventListener("keyup", onDocumentKeyUp, true);
function onDocumentKeyDown(event){
var keyCode = event.keyCode;
keyMap[keyCode] = true;
executeMovement();
}
function onDocumentKeyUp(event){
var keyCode = event.keyCode;
keyMap[keyCode] = false;
executeMovement();
}
function executeMovement(){
var cameraNeck = cameraEquipment.getNeck();
if(keyMap[37] == true){
//rotate left
}
if(keyMap[39] == true){
//rotate right
}
if(keyMap[38] == true){
//move front
}
if(keyMap[40] == true){
//move back
}
This setup allows for simultaneous movement and rotation when two keys are pressed at once. However, there is a notable issue. If a user presses the up arrow first followed by the left arrow (without releasing the up arrow), everything functions as intended and the user rotates to the left. But if the user releases the last pressed button (left arrow), both movement and rotation halt.
It appears that in the sequence of key presses, triggering a 'keyUp' event for one button may also trigger a 'keyUp' event for another button. This behavior has led me to question the overall implementation and debugging strategies employed thus far.