I'm going to make this very simple. Every frame, I need to render the 'player' wherever they are. Using setInterval, I was able to do this. Unfortunately, that causes it to occasionally flicker and my many hours trying to correct this have been unsuccessful. I've narrowed down the problem to inside this code:
function eachFrame(){
ctx.clearRect(0,0,canvas.width,canvas.height);
player.motion();
player.render();
setTimeout(window.requestAnimationFrame(eachFrame), 1000 / fps);
};
window.requestAnimationFrame(eachFrame);
When this runs, absolutely nothing appears onscreen.
player.motion updates the player position and handle movement logic. It is not the issue, but I need it.
player.render draws the current player position on the screen. It also is not the problem.
The reason I know player.motion and player.render are completely fine is because, when you get rid of ctx.clearRect(), you can move the player around and it renders perfectly.
function eachFrame(){
//ctx.clearRect(0,0,canvas.width,canvas.height);
player.motion();
player.render();
setTimeout(window.requestAnimationFrame(eachFrame), 1000 / fps);
};
window.requestAnimationFrame(eachFrame);
When you get rid of that, of course you're now playing snake and you're left with a trail behind the player. ctx.clearRect does it's job, it clears the screen.
This line is the problem:
setTimeout(window.requestAnimationFrame(eachFrame), 1000 / fps);
How do I fix it?