Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

223
Visualizações
Javascript - simple requestAnimationFrame gameloop

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?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda