0

How to create good timer for HTML5 Canvas games? I am using RequestAnimationFrame( http://paulirish.com/2011/requestanimationframe-for-smart-animating/ )

But object's move too fast.

Something like my code is:

http://pastebin.com/bSHCTMmq

But if I press UP_ARROW player don't move one pixel, but move 5, 8, or 10 or more or less pixels. How to do if I press UP_ARROW player move 1 pixel?

Thanks for help.

kichu
  • 53
  • 5
  • 1
    Personally I call my redraw function both from a timer (approximate time interval) and at each major "events" (user key, other player data sent by the server, etc.). – Denys Séguret May 30 '12 at 14:32
  • See ! http://stackoverflow.com/questions/19764018/controlling-fps-with-requestanimationframe –  Jun 19 '16 at 00:42

1 Answers1

0

The problem is that your approach of incrementing a value on each interval produces inconsistent results. Sounds like in your case RequestAnimationFrame is triggering too fast, but in other cases -- like on a slow CPU -- they would trigger slower, giving different results.

So, game animations need to be based on "absolute" time. Ie, you need to "remember" when the UP_ARROW was pressed, and where the player was at that point. Then, when you call update() determine how much time elapsed, and based on that, and the desired speed (in, say, pixels per second), move the player to the appropriate position. It makes your code more complicated, but unfortunately that's how it has to be done.

This issue is discussed a lot online. Here's one random article I found (based on Flash, but it doesn't matter): http://www.flashgamesclassroom.com/classroom/actionscript/frame-based-vs-time-based-animation/

You can google "time based game animation" to research more.

meetamit
  • 24,727
  • 9
  • 57
  • 68