您好,我正在尝试编写经典的Pong游戏。我正在尝试实现平稳的移动,因此当释放钥匙时,它应逐渐减速至停止。我一直在关注一些教程,但似乎无法弄清楚。

我注意到,如果您按住向上箭头一点然后让它移动然后向下按住箭头,它仍然会沿向上方向移动一点然后开始向下移动。你知道这是怎么回事吗?

这是我的代码:



var canvas;
var canvasContext;

var x = 5,
  y = 150;
var velY = 0;
var speed = 50;
var friction = 0.9;

window.onload = function() {
  canvas = document.getElementById("gameCanvas");
  canvasContext = canvas.getContext("2d");

  var fps = 30;
  setInterval(function() {
    draw();
  }, 1000 / fps); // 1000miliseconds = 1 seconds

  document.addEventListener("keydown",
    function(event) {
      var x = event.key;

      switch (x) {
        case 'ArrowDown':
          key_down();
          velY *= friction;
          y += velY;
          break;
        case 'ArrowUp':
          key_up();
          velY *= friction;
          y += velY;
          break;
      }
    });
}

function key_up() {
  if (velY > -speed)
    velY--;
}

function key_down() {
  if (velY < speed)
    velY++;
}

function draw() {
  //canvas background color
  colorRect(0, 0, canvas.width, canvas.height, "black");

  //left player paddle
  colorRect(x, y, 15, 100, "white");
}

function colorRect(leftX, topY, width, height, drawColor) {
  canvasContext.fillStyle = drawColor;
  canvasContext.fillRect(leftX, topY, width, height);
}

<canvas id="gameCanvas" width="600" height="400" style="border:1px solid black;"></canvas>

最佳答案

它的编程方式将使其速度降低,然后再朝另一个方向移动。如果先将速度设置为0,它将开始直接移动。

function key_up() {
  velY = 0; // Set to zero to stop paddle
  if (velY > -speed)
    velY--;
}

function key_down() {
  velY = 0; // Set to zero to stop paddle
  if (velY < speed)
    velY++;
}

关于javascript - 这个 Canvas 运动怎么了,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58824121/

10-12 13:21