两位玩家如何同时移动(JS游戏)

时间:2020-06-08 21:43:51

标签: javascript

И有一个使用javascript进行的曲棍球游戏,但玩家不能同时移动。实际上,当一个移动时,另一个保持静止。两名玩家在此游戏中同时移动是正常的。您知道可以帮助我的功能吗?是否应该添加外部功能?谢谢您的帮助。

    <html>
    <head>
        <style>
            body {
                margin: 0;
            }
            .P1 {
                position: absolute;
                font-size: 110px;
                background-color: white;
            }
            .P2 {
                position: absolute;
                left: 1500px;
                font-size: 110px;
                background-color: white;
            }
        </style>
    </head>
    <body onkeydown="keyD(event)">
        <span class="P1">|</span>
        <span class="P2">|</span>
    </body>
    <script>
        var P1D = 0;
        var P2D = 0;
        var spanP1 = document.getElementsByClassName("P1")[0];
        var spanP2 = document.getElementsByClassName("P2")[0];
        function keyD(e) {
            if (e.keyCode == 38 || e.keyCode == 40) {
                f1(e);
            }
            if (e.keyCode == 83 || e.keyCode == 87) {
                f2(e);
            }
        }
        function f1(e) {
            if (e.keyCode == 40) {
                if (P2D >= 620) {
                } else {
                    P2D += 10;
                    spanP2.style.top = P2D + "px";
                }
            }
            if (e.keyCode == 38) {
                if (P2D <= -20) {
                } else {
                    P2D -= 10;
                    spanP2.style.top = P2D + "px";
                }
            }
        }
        function f2(e) {
            if (e.keyCode == 83) {
                if (P1D >= 620) {
                } else {
                    P1D += 10;
                    spanP1.style.top = P1D + "px";
                }
            }
            if (e.keyCode == 87) {
                if (P1D <= -20) {

                } else {
                    P1D -= 10;
                    spanP1.style.top = P1D + "px";
                }
            }
        }
    </script>
    </html>

1 个答案:

答案 0 :(得分:1)

您需要记住是否按下了哪些键。例如,通过将其状态保存在对象中。

此外,当玩家1按下一个键并且玩家2开始按下另一个键时,玩家1的键会暂时停止重复。为避免这种情况,您将需要停止依赖用户系统的按键重复。例如,通过使用setInterval或更高版本将其实现到游戏循环中。示例:

// Save key states in an object
const keystates = {}
document.addEventListener('keydown', e => {
    keystates[e.code] = true
})
document.addEventListener('keyup', e => {
    keystates[e.code] = false
})

// Repeat the key action in your gameloop
const repeat_interval = 500
setInterval(() => {
    if (keystates['KeyW']) console.log('Player1 up')
    if (keystates['KeyS']) console.log('Player1 down')
    if (keystates['ArrowUp']) console.log('Player2 up')
    if (keystates['ArrowDown']) console.log('Player2 down')
}, repeat_interval)

编辑: 同样不要使用deprecatedkeyCode