The problem is that my function executes only once after using setInverval(). Anyone knows how to fix it so update() method of the snake object actually runs over and over again?
Here is the code:
let canvas = document.getElementById("cnvs");
ctx = canvas.getContext("2d");
canvas.width=500;
canvas.height=500;
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
let step = canvas.width / 15;
let snake = new Snake(1);
console.log(snake);
setInterval(snake.update(),1000);
setInterval(snake.draw(),1000);
function Snake(dir) {
this.x = 300;
this.y = 300;
this.dir = dir;
this.step=step;
this.update = function () {
if (this.dir === 1) {
console.log(this.y);
this.y-=this.step;
console.log(this.y);
}
else if (this.dir === 2) {
this.x+=this.step;
}
else if (this.dir === 3) {
this.y+=this.step;
}
else if (this.dir === 4) {
this.x-=this.step;
}
}
this.draw = function () {
ctx.fillStyle = "red";
ctx.fillRect(this.x,this.y,step,step);
}
}