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