仅当用户按住键时才使变量返回true

时间:2016-05-11 16:30:51

标签: javascript pong

我在Javascript中重新创建经典乒乓球游戏,我有一个更新游戏状态然后重绘整个游戏的循环。

设置游戏的高度:

var leftHeight = 225;
var rightHeight = 225;

桨状态和改变状态的关键:

var keyWPressed = false;
var keySPressed = false;
var keyArrowUpPressed = false;
var keyArrowDownPressed = false;

window.addEventListener('keydown', function (evt) {
    if (evt.keyCode === 87) {
        keyWPressed = true;
        keySPressed = false;    // the player can hold down both keys at once, but 
                                // we want the last pressed key to take precedence
    } else if (evt.keyCode === 83) {
        keySPressed = true;
        keyWPressed = false;   // last keypress takes precedence
    } else if (evt.keyCode === 38) { // up arrow
        keyArrowUpPressed = true;
        keyArrowDownPressed = false;  // last keypress takes precedence
    } else if (evt.keyCode === 40) {  // down arrow
        keyArrowDownPressed = true;
        keyArrowUpPressed = false;  // last keypress takes precedence
    } else if (evt.keyCode === 82) {  // 'r'
        // when a player has won, hitting 'r' resets the game
        if (winner) {
            restartGame();
        }
    }
});

更新桨状态并循环游戏:

function update(){
    if (keyWPressed && leftHeight != 0){
        leftHeight = leftHeight - 5;
    }else if (keySPressed && leftHeight != 450){
        leftHeight = leftHeight + 5;
    }
    if (keyArrowUpPressed && rightHeight != 0){
        rightHeight = rightHeight - 5;
    }else if (keyArrowDownPressed && rightHeight != 450){
        rightHeight = rightHeight + 5;
    }
}

function gameloop(){
    update();
    draw();
    window.requestAnimationFrame(gameloop);
}

问题是,每当我按下一个键,例如W键时,当我真正想要的只是当玩家按下并按住W时,只需按一下按钮即可向上移动。键。

0 个答案:

没有答案