【问题标题】:How can I move my JS objects smoothly using keyboard input?如何使用键盘输入平滑地移动我的 JS 对象?
【发布时间】:2015-11-23 21:19:58
【问题描述】:

所以我是 HTML5 新手,并决定开始编写乒乓球游戏。我想用我的键盘流畅地移动我的角色,左边那个是 W 和 S 键,右边那个是向上和向下箭头。我似乎无法让它工作。这可能很容易,但我是菜鸟,我需要一些帮助。提前致谢!

<!DOCTYPE html>
<html>
  <head>
      <title>Pingedy Pong</title>
  </head>
  <body style="font-family:Arial;">
      <canvas id="ctx" width="699" height="400" style="background-color:black;border:2px solid black;background-image: url('background.jpg');"></canvas>
      <script>
        
        // STARTING SCRIPT
          
        var ctx = document.getElementById("ctx").getContext("2d");
        ctx.fillStyle="white";
        ctx.font = '30px Arial';
        
        // VARIABLES
          
        var keys1 = [];
        var keys2 = [];
          
        var width = 699;
        var height = 400;
          
        var ball = {
            width:20,
            height:20,
            spdX:2.9,
            spdY:2.9,
            x:340,
            y:190,
        };
          
        var char1 = {
            w:15,
            h:90,
            spdX:3,
            spdY:3,
            x:10,
            y:155,
        };
          
        var char2 = {
            w:15,
            h:90,
            spdX:3,
            spdY:3,
            x:674,
            y:155,
        };
          
          // UPDATE
          
          function updateEntity(a) {
            a.x+=a.spdX;
            a.y+=a.spdY;
            ctx.clearRect(0,0,width,height);
            ctx.fillRect(a.x,a.y,a.height,a.width);
              if(a.x > width-a.width || a.x < 0) {
                a.spdX = -a.spdX;
              };
              
              if(a.y > height-a.height || a.y < 0) {
                a.spdY = -a.spdY;
              };
          };
          
          function renderChar(b) {
            ctx.fillRect(b.x,b.y,b.w,b.h);
          };
          
          function checkInput() {
            document.addEventListener('onkeydown', function(e) {
                if(e.keyCode == 37) {
                    char1.y += 1;
                }
                else if(e.keyCode == 39) {
                    char1.y -= 1;
                }
            });
          };
          
          function checkWinP1() {
              if (ball.x < 0.33) {
                console.log("P1 Wins");
              };
          };
          function checkWinP2() {
              if (ball.x > 679) {
                console.log("P2 Wins");
              };
          };
          
          function update() {
            updateEntity(ball);
            renderChar(char1);
            renderChar(char2);
            checkInput();
            checkWinP1();
            checkWinP2();
          };
          
          //TICKS
          
          setInterval(update,1000/120);
             
     </script>
  </body>
</html>

【问题讨论】:

  • 哪一点特别不起作用?

标签: javascript jquery css html


【解决方案1】:

更新 1:使用 keydown 而不是 keypress 事件。

此更新的原因是箭头键don't triggerkeypress 事件(或者它们触发它但事件不返回有关按下哪个键的信息)。如果您想了解更多信息,请阅读this


更新 2

我现在意识到您问题中的“smoothly”关键字。如果调用update 函数的间隔太短对你来说不够好,requestAnimationFrame() API is the way to go


当您编写游戏时,我建议您使用 jQuery。

试试这个代码:

var characterSpeed = 15;

$(document).on("keydown", function (e) {
    switch (e.which)
    {
        case 87: //w
            char1.y -= characterSpeed;
            break;
        case 83: //s
            char1.y += characterSpeed;
            break;
        case 38: //up arrow
            char2.y -= characterSpeed;
            break;
        case 40: //down arrow
            char2.y += characterSpeed;
            break;
        default:
            alert("You have pressed the key " + e.which);
     } 
});

这里有sn-p:

// STARTING SCRIPT
          
        var ctx = document.getElementById("ctx").getContext("2d");
        ctx.fillStyle="white";
        ctx.font = '30px Arial';
        
        // VARIABLES
          
        var keys1 = [];
        var keys2 = [];
          
        var width = 699;
        var height = 400;
          
        var ball = {
            width:20,
            height:20,
            spdX:2.9,
            spdY:2.9,
            x:340,
            y:190,
        };
          
        var char1 = {
            w:15,
            h:90,
            spdX:3,
            spdY:3,
            x:10,
            y:155,
        };
          
        var char2 = {
            w:15,
            h:90,
            spdX:3,
            spdY:3,
            x:674,
            y:155,
        };
          
          // UPDATE
          
          function updateEntity(a) {
            a.x+=a.spdX;
            a.y+=a.spdY;
            ctx.clearRect(0,0,width,height);
            ctx.fillRect(a.x,a.y,a.height,a.width);
              if(a.x > width-a.width || a.x < 0) {
                a.spdX = -a.spdX;
              };
              
              if(a.y > height-a.height || a.y < 0) {
                a.spdY = -a.spdY;
              };
          };
          
          function renderChar(b) {
            ctx.fillRect(b.x,b.y,b.w,b.h);
          };
          
          function checkInput() {
            document.addEventListener('onkeydown', function(e) {
                if(e.keyCode == 37) {
                    char1.y += 1;
                }
                else if(e.keyCode == 39) {
                    char1.y -= 1;
                }
            });
          };
          
          function checkWinP1() {
              if (ball.x < 0.33) {
                console.log("P1 Wins");
              };
          };
          function checkWinP2() {
              if (ball.x > 679) {
                console.log("P2 Wins");
              };
          };
          
          function update() {
            updateEntity(ball);
            renderChar(char1);
            renderChar(char2);
            checkInput();
            checkWinP1();
            checkWinP2();
          };
          
          //TICKS
          
          setInterval(update,1000/120);


    //NEW CODE TO MANAGE THE CHARACTERS MOTION

    var characterSpeed = 15;

    $(document).on("keydown", function (e) {
        switch (e.which)
        {
            case 87: //w
                char1.y -= characterSpeed;
                break;
            case 83: //s
                char1.y += characterSpeed;
                break;
            case 38: //up arrow
                char2.y -= characterSpeed;
                break;
            case 40: //down arrow
                char2.y += characterSpeed;
                break;
            default:
                alert("You have pressed the key " + e.which);
         } 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
      <title>Pingedy Pong</title>
  </head>
  <body style="font-family:Arial;">
      <canvas id="ctx" width="699" height="400" style="background-color:black;border:2px solid black;background-image: url('background.jpg');"></canvas>
      <script>
        

     </script>
  </body>
</html>

另外,您可能想阅读以下两篇文章:

您将了解如何将多个处理程序绑定到同一个事件、IE 和其他浏览器之间的区别、String.fromCharCode 函数以及如果您有兴趣,如何使用 vanilla 编写相同的代码javascript。

希望对你有帮助!

【讨论】:

  • 谢谢!我会试试看! :D
猜你喜欢
  • 2012-12-14
  • 1970-01-01
  • 1970-01-01
  • 2017-08-14
  • 1970-01-01
  • 1970-01-01
  • 2011-04-30
  • 2020-12-01
  • 2014-06-28
相关资源
最近更新 更多