Reputation: 8908
I am creating a webGL game, using Three.js library. I am creating movement in the space with keyboard arrows. I want to enable user to simultaneously rotating and moving by pressing the left-right arrow together with the up-down arrow. For this reason, I have created a map holding the status of all needed keys. The used code is the following :
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
}
It works, meaning that when a user holds down 2 keys in the same time, he moves and rotates simultaneously. However, it has the following problem. For example, let assume the user presses first the up arrow, and then (without leaving it), he presses the left arrow. If he then leaves the button that was pressed first (up arrow), everything works as expected and the user is left rotating left. However, if the user leaves the button pressed last (left arrow), the user then stops moving and rotating both.
It seems that in the sequence of key presses, the event of 'keyUp' of the one button triggers 'keyUp' for the other one, or something like that. I have tried many different ways of debugging and I have started considering the possibility that there is something wrong with the whole implementation.
Upvotes: 1
Views: 1458
Reputation: 8908
As I was thinking there was no error in the implementation of the map holding the status of the keys. This was working successfully. The problem was with the function executeMovement()
, which was only called once after 'keydown' or 'keyup' event. So, this is why the user stopped moving having one key still pressed.
This function should be called inside the function that was called when browser was renewing the frame. So, the fixed code is the following :
var keyMap = [];
document.addEventListener("keydown", onDocumentKeyDown, true);
document.addEventListener("keyup", onDocumentKeyUp, true);
function onDocumentKeyDown(event){
var keyCode = event.keyCode;
keyMap[keyCode] = true;
}
function onDocumentKeyUp(event){
var keyCode = event.keyCode;
keyMap[keyCode] = false;
}
function executeMovement(){
\\same code
}
var render = function () {
requestAnimationFrame( render );
renderer.render(scene, cameraEquipment.getCamera());
executeMovement()
};
render();
Upvotes: 2