【问题标题】:Smoother movement or diagonal movement - Javascript更平滑的移动或对角线移动 - Javascript
【发布时间】:2023-03-26 23:41:01
【问题描述】:

我正在尝试让我的<div> 移动得更平滑或沿对角线移动。当按下WD 等两个键时,它只向一个方向移动。我想让它对角移动。有没有一种可能的方法可以使运动不那么起伏不定。 divShootingGallery 是父 <div> 或游戏板,divShooter 是临时框。我只想使用 JavaScript 而不是 jQuery。

这是我的代码:

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

【问题讨论】:

    标签: javascript animation keyevent


    【解决方案1】:

    您的 keyClick() 函数中缺少“事件”

    function ketClick(event) {
      ...
    }
    

    【讨论】:

      【解决方案2】:

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

      基本上,您必须实现 keydown 和 keyup 事件,并注意当前哪些键处于关闭状态。然后您应该在模拟循环中使用该信息以正确移动对象。模拟循环可以是这样的计时器:

      function moveObject() {
          ... check which keys are down and move accordingly ...
      }
      
      setInterval(function() {
          moveObject();
      }, 100);
      

      【讨论】:

        猜你喜欢
        • 2021-10-17
        • 1970-01-01
        • 2020-08-12
        • 1970-01-01
        • 2013-06-05
        • 2011-04-30
        • 2017-11-07
        • 2021-12-20
        • 1970-01-01
        相关资源
        最近更新 更多