문제

I'm very new to programming and I'm trying to create some code that will allow me to move a square around the Canvas by pressing arrow keys. I'm able to get the square to move, but its motion isn't very smooth. I have it moving by increments of 10 pixels at a time, so I understand why it feels kind of jerky, because there isn't any animation between each position of 10-frames-difference, but having it move by smaller increments makes it far too slow. What I've done so far is below:

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

Every time I press the arrow key right, I would like for the square to move smoothly in that direction at a constant rate. Thanks in advance for any help at all!

도움이 되었습니까?

해결책

Added a few things, the first is requestAnimationFrame for reasons explained here.

I then added a keyup and keydown event handler, these will keep track of what keys are currently being pushed by using an array. If the key is true in the array its currently being pushed, if false it isn't. This method also allows you to press and hold multiple keys at once.

I then added velocity variables which increase or decreased based on whats being pressed, and a maxSpeed variable so you don't go faster than a certain speed. The maxSpeed variable could be removed and the incrementing and decrementing velX and velY could also be removed, you would just need to uncomment the lines I left. It just seemed to go too fast at 10 thats why I added the gradual speed up.

Live Demo

The above will seem jerky, because the frame is scrolling with the up and down arrows since the canvas is a bit bitter, use the full screen link to fully test the movement.

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;
    }
  }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top