Search code examples
javascriptgame-loop

My Game loop accelerates and character leaves a trail


The code:

// create stuff
var ghObj = {
x : 0,
y : 0
}
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ghost = new Image();
ghost.src = "ghost.png"

//define variables
var ghostMove = function () {
    ghObj.x+=(Math.floor(Math.random() * 9 - 4))
    console.log(ghObj.x)
    ghObj.y+=(Math.floor(Math.random() * 9 - 4))
}

var ghostCheck = function () {
    if (ghObj.x<0) {
        ghObj.x=0
    }
    if (ghObj.x>390) {
        ghObj.x=390
    }
    if (ghObj.y<0) {
        ghObj.y=0
    }
    if (ghObj.y>390) {
        ghObj.y=390
    }
}

var drawIm = function (sprite, position) {
    ctx.save();
    ctx.translate(position.x, position.y);
    ctx.drawImage(sprite, 0, 0, sprite.width, sprite.height, 0, 0, sprite.width, sprite.height);
    ctx.restore();
};

// begin "game" when ghost is loaded
ghost.onload = function() {
    mainLoop()
}

// main loop
    function() {

    ghostMove()

    ghostCheck()

    drawIm(ghost, ghObj)

    setInterval(mainLoop, 1000) 
}

sorry if its a bit long.

what's supposed to happen is the ghost moves randomly round the screen at a steady rate. instead, it moves randomly but increasingly quickly and leaves copies of itself everywhere.

Isn't the restore function supposed to clear the screen each time?

have i got the game loop wrong? thanks in advance.


Solution

  • function mainLoop(){
      setInterval(mainLoop,100);
    }
    

    I think the error is obvious. I recommend to use setTimeout or requestAnimationFrame instead... And this should remove the duplicates i think its an optical ilusion ...