我对编程很陌生,我正在尝试创建一些代码,让我可以通过按箭头键在 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;
}
}
每次我按右箭头键时,我都希望方块以恒定的速率向那个方向平滑移动。提前感谢您的任何帮助!