SasukeRinnegan
SasukeRinnegan

Reputation: 129

Understanding key codes with arrays

so there's this code I found online and it helps me control my sprite with keys, but I'm not quite sure how it works. Can someone please describe to me in some level of detail how the array works into the key codes, etc.

It basically gets the left and right and space bar keys to work.

    var keys = [];  

    //This is part of a class
    this.listenInput = function() {
            if (keys[37]) {
                this.x -= speed; 
            }
            if (keys[39]) {
                this.x += speed;
            }
        };


function setupKeys() {
    var listenedKeys = [32, 37, 38, 39, 40];

    function keyUpHandler(event) {
       var keyCode = event.keyCode;
       if (listenedKeys.indexOf(keyCode) === -1) return;
       keys[keyCode] = false;        
    }
       function keyDownHandler(event) {
            var keyCode = event.keyCode;
            if (listenedKeys.indexOf(keyCode) === -1) return;
            keys[keyCode] = true;        
            if (keyCode === 32) {
               spaceBarPressed = true;
            }
           event.preventDefault();
        }

        //Event listeners for keys
        window.addEventListener("keydown", keyDownHandler, false);
        window.addEventListener("keyup", keyUpHandler, false);
    }

Upvotes: 0

Views: 373

Answers (1)

Amadan
Amadan

Reputation: 198446

A browser can't tell you whether a key is pressed or not. It only knows when a key gets pressed or depressed. So you have to track the state of the key yourself. When a key is pressed (keyDownHandler), you remember it is pressed. When a key is depressed (keyUpHandler), you remember that it is not. This allows your game loop to react on continuous button mash rather than only reacting once when pressed, or relying on autorepeat to trigger.

Upvotes: 1

Related Questions