如何使用键盘输入平稳地移动我的JS对象? [英] How can I move my JS objects smoothly using keyboard input?

查看:72
本文介绍了如何使用键盘输入平稳地移动我的JS对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我是HTML5的新手,并决定开始编码乒乓球比赛。我想用我的键盘顺利地移动我的角色,左侧的W和S键以及右侧的上下箭头。我似乎无法得到它的工作。这可能很容易,但我是我的noob,我需要一些帮助。提前致谢!



 <!DOCTYPE html>< html> < HEAD> < title> Pingedy Pong< / title> < /头> < body style =font-family:Arial;> < canvas id =ctxwidth =699height =400style =background-color:black; border:2px solid black; background-image:url('background.jpg');><<<<<< ; /画布> <脚本> //启动脚本var ctx = document.getElementById(ctx)。getContext(2d); ctx.fillStyle = 白色; 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,}; //更新函数updateEntity(a){a.x + = a.spdX; a.y + = a.spdY; ctx.clearRect(0,0,宽度,高度); ctx.fillRect(a.x,a.y,a.height,a.width); if(a.x> width-a.width || a.x< 0){a.spdX = -a.spdX; };如果(a.y> height-a.height || a.y< 0){a.spdY = -a.spdY; }; };函数renderChar(b){ctx.fillRect(b.x,b.y,b.w,b.h); };函数checkInput(){document.addEventListener('onkeydown',function(e){if(e.keyCode == 37){char1.y + = 1;} else if(e.keyCode == 39){char1.y -  = 1;}}); };函数checkWinP1(){if(ball.x <0.33){console.log(P1 Wins); }; };函数checkWinP2(){if(ball.x> 679){console.log(P2 Wins); }; };函数update(){updateEntity(ball); renderChar(CHAR1); renderChar(CHAR2); checkInput(); checkWinP1(); checkWinP2(); }; // TICKS setInterval(update,1000/120); < /脚本> < / body>< / html>  

解决方案更新1 :使用 keydown 而不是按键事件。

此次更新的原因是,箭头键不触发 a> 按键事件(或者它们会触发它,但事件不会返回关于哪个键被按下的信息)。阅读,当你想知道更多关于它的信息。






UPDATE 2



我现在认识到' smooth '关键字你的问题。如果短时间间隔调用 update 函数对您来说不够好, requestAnimationFrame() API 是要走的路




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



试试这段代码:

  var characterSpeed = 15; 
$ b $(document).on(keydown,function(e){
switch(e.which)
{
case 87:// w
char1.y - = characterSpeed;
break;
case 83:// s
char1.y + = characterSpeed;
break;
case 38: //向上箭头
char2.y - = characterSpeed;
break;
case 40://向下箭头
char2.y + = characterSpeed;
break;
默认值:
alert(您已按下+ e.which);
}
});

在这里您可以看到:



//启动脚本var ctx = document.getElementById ctx.fillStyle = 白色; 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,}; //更新函数updateEntity(a){a.x + = a.spdX; a.y + = a.spdY; ctx.clearRect(0,0,宽度,高度); ctx.fillRect(a.x,a.y,a.height,a.width); if(a.x> width-a.width || a.x< 0){a.spdX = -a.spdX; };如果(a.y> height-a.height || a.y< 0){a.spdY = -a.spdY; }; };函数renderChar(b){ctx.fillRect(b.x,b.y,b.w,b.h); };函数checkInput(){document.addEventListener('onkeydown',function(e){if(e.keyCode == 37){char1.y + = 1;} else if(e.keyCode == 39){char1.y - = 1;}}); };函数checkWinP1(){if(ball.x <0.33){console.log(P1 Wins); }; };函数checkWinP2(){if(ball.x> 679){console.log(P2 Wins); }; };函数update(){updateEntity(ball); renderChar(CHAR1); renderChar(CHAR2); checkInput(); checkWinP1(); checkWinP2(); }; // TICKS setInterval(update,1000/120); //新代码来管理字符运动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://向上箭头char2.y - = characterSpeed; break; case 40://向下箭头char2.y + = characterSpeed; break; default:alert(您已按下键+ 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> < /头> < body style =font-family:Arial;> < canvas id =ctxwidth =699height =400style =background-color:black; border:2px solid black; background-image:url('background.jpg');><<<<<< ; /画布> <脚本> < /脚本> < / body>< / html>

也许想阅读这两个帖子:



您将会了解如何绑定同一个事件的多个处理程序,IE与其他浏览器之间的区别, String.fromCharCode 函数,如果您有兴趣,可以使用相同的代码香草javascript。



希望它有帮助!


So I am new to HTML5 and decided to start to code a pong game. I want to move my characters smoothly using my keyboard, the W and S keys for the one on the left and the Up and Down arrows for the one on the right. I can't seem to get it to work. It's probably quite easy, but me being the noob I am, I need a bit of help. Thanks in advance!

<!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>

解决方案

UPDATE 1: use keydown instead of keypress event.

The reason for this update is that arrow keys don't trigger the keypress event (or they trigger it but the event doesn't return information about which key was pressed). Read this when you want more information about it.


UPDATE 2

I realize now the 'smoothly' keyword in your question. If to call the update function with a short interval is not good enough for you, requestAnimationFrame() API is the way to go.


When you are programming a game, I advice you to use jQuery.

Try this code:

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);
     } 
});

Here you have the snippet:

// 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>

Also, you maybe want to read this two posts:

You will get to know about how to bind multiple handlers to the same event, the difference between IE and the rest of the browsers, the String.fromCharCode function and, if you are interested, how to write the same code with vanilla javascript.

Hope it helps!

这篇关于如何使用键盘输入平稳地移动我的JS对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆