在JavaScript中使用Canvas平滑keydown动画

我是编程的新手,我正在尝试创建一些代码,允许我通过按箭头键在Canvas周围移动一个方块.我能够让广场移动,但它的动作不是很平滑.我让它一次以10像素的增量移动,所以我理解为什么它会感觉有点生涩,因为10帧差异的每个位置之间没有任何动画,但让它以较小的增量移动会使它远太慢了.到目前为止我所做的工作如下:

window.onload = function init() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    setInterval(gameLoop,50);
    window.addEventListener('keydown',whatKey,true);
}

avatarX = 400
avatarY = 300

function gameLoop() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    canvas.width = 800
    canvas.height = 600
    ctx.fillRect(avatarX,avatarY,50,50);
}

function whatKey(e) {
    switch(e.keyCode) {
    case 37:
        avatarX = avatarX - 10;
        break;
    case 39:
        avatarX = avatarX + 10;
        break;
    case 40:
        avatarY = avatarY + 10;
        break;
    case 38:
        avatarY = avatarY - 10;
        break;
    }
}

每次我按下右箭头键,我都希望广场以恒定的速度在那个方向上平稳移动.在此先感谢任何帮助!

解决方法:

添加了一些东西,第一个是requestAnimationFrame for reasons explained here.

然后我添加了一个keyup和keydown事件处理程序,它们将使用数组跟踪当前正在推送的键.如果数组中的键为true,则当前正在推送它,如果为false,则不是.此方法还允许您一次按住多个键.

然后我添加了速度变量,这些变量根据按下的内容而增加或减少,以及maxSpeed变量,因此您不会比某个速度快.可以删除maxSpeed变量,也可以删除递增和递减的velX和velY,您只需要取消注释我留下的行.它似乎在10点太快了,这就是为什么我加上渐进的速度.

Live Demo

上面看起来很生涩,因为框架是用向上和向下箭头滚动的,因为画布有点苦,使用全屏链接来完全测试运动.

Full Screen link

(function () {
  var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame;
  window.requestAnimationFrame = requestAnimationFrame;
})();


window.onload = function init() {
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  gameLoop();
}

window.addEventListener("keydown", function (e) {
  keys[e.keyCode] = true;
});
window.addEventListener("keyup", function (e) {
  keys[e.keyCode] = false;
});


var avatarX = 400,
  avatarY = 300,
  velX = 0,
  velY = 0,
  keys = [],
  maxSpeed = 10;

function gameLoop() {
  whatKey();
  var canvas = document.getElementById("canvas");
  var ctx = canvas.getContext("2d");
  canvas.width = 800;
  canvas.height = 600;

  avatarX += velX;
  avatarY += velY;

  ctx.fillRect(avatarX, avatarY, 50, 50);
  requestAnimationFrame(gameLoop);
}

function whatKey() {
  if (keys[37]) {
    //velX = -10;
    if (velX > -maxSpeed) {
      velX -= 0.5;
    }
  }

  if (keys[39]) {
    //velX = 10;
    if (velX < maxSpeed) {
      velX += 0.5;
    }
  }
  if (keys[40]) {
    //velY = 10;
    if (velY < maxSpeed) {
      velY += 0.5;
    }
  }
  if (keys[38]) {
    //velY = -10;
    if (velY > -maxSpeed) {
      velY -= 0.5;
    }
  }
}
上一篇:maven项目搭建步骤


下一篇:python – 图像在Pygame中旋转,同时保持光滑的边缘