lundi 29 mai 2017

Dealing with user holding key down in JavaScript EventListener

So I am making a simple javascript game and I am using the spacebar to shoot missles.

Here is where I have problems:

        document.addEventListener("keydown", keyDownHandler, false);
        document.addEventListener("keyup", keyUpHandler, false);

        function keyDownHandler(e){
            if(e.keyCode == 39){
                rightPressed = true;
            }
            else if(e.keyCode == 37){
                leftPressed =true;
            }
            else if(e.keyCode == 32){  //Keycode for space bar
                missleFired = true;
            }
        }

        function keyUpHandler(e){
            if(e.keyCode == 39){
                rightPressed = false;
            }
            else if(e.keyCode == 37){
                leftPressed = false;
            }
        }

In my keyDownHandler, I am using it to catch when the user is moving the spaceship left and right, or when the user presses spacebar to shoot. Problem is, I only want the "missleFired" variable to be set to true once, initially when the bar is pressed. The way it is right now, the user can hold the spacebar down and shoot loads of missles, but I want only one missle to be shot from the time the spacebar is held down until it is released. How can I do this?




Aucun commentaire:

Enregistrer un commentaire