When I move the object, it's slow and doesn't move in diagonal, only up, down, right and left.
How can I fix this, is this a good way to start or should I do it otherwise?
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext('2d');
canvas.width = 600;
canvas.height = 600;
var object = {
height: 40,
width: 40,
x: 10,
y: 10,
color: "#FF0000"
}
document.addEventListener('keydown', function(event) {
//left
if(event.keyCode == 37) {
object.x -= 1;
}
//top
else if(event.keyCode == 38) {
object.y -= 1;
}
//right
else if(event.keyCode == 39) {
object.x += 1;
}
//bottom
else if(event.keyCode == 40) {
object.y += 1;
}
});
function renderCanvas(){
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 600, 600);
}
function renderObject(){
ctx.fillStyle = "#FF0000";
ctx.fillRect(object.x, object.y, object.width, object.height);
}
function run(){
renderCanvas();
renderObject();
}
setInterval(run, 10);
Here's a jsfiddle
I'm kind of a newbie in javascript and I really need help on this ;)
Use flags or an object with flags that is updated when keys are pressed and released:
var Keys = {
up: false,
down: false,
left: false,
right: false
};
Then update in key events:
window.onkeydown = function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) Keys.left = true; // only one key per event
else if (kc === 38) Keys.up = true; // so check exclusively
else if (kc === 39) Keys.right = true;
else if (kc === 40) Keys.down = true;
};
window.onkeyup = function(e) {
var kc = e.keyCode;
e.preventDefault();
if (kc === 37) Keys.left = false;
else if (kc === 38) Keys.up = false;
else if (kc === 39) Keys.right = false;
else if (kc === 40) Keys.down = false;
};
This will now allow you to check keys that are pressed at the same time (if you want to move continuously you need to check status of the key object in a loop or else you will get a repeat delay):
if (Keys.up) {
dy+=3;
}
else if (Keys.down) { // both up and down does not work so check excl.
dy-=3;
}
if (Keys.left) {
dx+=3;
}
else if (Keys.right) {
dx-=3;
}