更平滑的运动或对角线运动 - Javascript

时间:2018-03-10 08:03:13

标签: javascript animation keyevent

我试图让<div>移动得更顺畅或更对角。当按下WD这两个键时,它只向一个方向移动。我想让它对角移动。有没有办法让机芯不那么波动。 divShootingGallery是父<div>或游戏板,divShooter是临时包装箱。我想只使用JavaScript而不是jQuery。

这是我的代码:

&#13;
&#13;
function keyClick(){
  var divShooter = document.getElementById("divShooter");
  var divGameBoard = document.getElementById("divShootingGallery");

  switch(event.keyCode)
    {
    case 65://a to move left
      if(divShooter.offsetLeft > 0){
        //checks to make sure the left side of the shooter is not off the left side
        divShooter.style.left = divShooter.offsetLeft - 10 + "px";
      }else{
        divShooter.style.left = "0px";
      }
    break;
    case 68://d to move right
      if(divShooter.offsetLeft + divShooter.clientWidth < divGameBoard.clientWidth){
        //checks to make sure the right side of the shooter is not off the right side
        divShooter.style.left = divShooter.offsetLeft + 10 + "px";
        }
      else{
        divShooter.style.left = (divGameBoard.clientWidth - divShooter.clientWidth) + "px";
      }
    break;
    case 87://w key up for right player
      divShooter.style.top = divShooter.offsetTop - 10 + "px";
      if(divShooter.offsetTop <= 0){
      divShooter.style.top = "0";
      }
    break;
    case 83://s key down for right player
    divShooter.style.top = divShooter.offsetTop + 10 + "px";
      if(divShooter.offsetTop + divShooter.clientHeight >= divGameBoard.clientHeight){
      divShooter.style.top = divGameBoard.clientHeight - divShooter.clientHeight + "px";
      }
    break;
  }
}
window.addEventListener('keydown',keyClick,true);
&#13;
html,body{
  height:100%;
  width:100%;
  }
#divShootingGallery{
  position:absolute;
  left:0;
  right:0;
  margin:auto;
  width:1000px;
  height:600px;
  background:bisque;
}
#divShooter{
  position:absolute;
  left:475px;
  bottom:0;
  width:50px;
  height:50px;
  background:blue;
}
&#13;
<head>
  <link rel="stylesheet" href="style.css" type="text/css"/>
  <script type="text/javascript" src="script.js"></script>
</head>
<body>
  <div id="divShootingGallery">
    <div id="divShooter"></div>
  </div>
</body>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

你的keyClick()函数中缺少btw“event”

function ketClick(event) {
  ...
}

答案 1 :(得分:0)

请检查该线程,您的问题非常相似: Player movement in javascript with socket.io

基本上,您必须实现keydown和keyup事件,并记下当前按下了哪些键。然后,您应该在模拟循环中使用该信息,以便正确移动对象。模拟循环可以是这样的计时器:

function moveObject() {
    ... check which keys are down and move accordingly ...
}

setInterval(function() {
    moveObject();
}, 100);