{"id":816,"date":"2024-02-29T13:20:12","date_gmt":"2024-02-29T07:50:12","guid":{"rendered":"http:\/\/codetheory.in\/?p=816---ee8f87d2-d579-4cb0-ae4f-69d95fe912e9"},"modified":"2024-02-29T13:20:12","modified_gmt":"2024-02-29T07:50:12","slug":"time-based-animations-in-html5-games-why-and-how-to-implement-them","status":"publish","type":"post","link":"https:\/\/codetheory.in\/time-based-animations-in-html5-games-why-and-how-to-implement-them\/","title":{"rendered":"Time Based Animations in HTML5 Games: Why and How to Implement them"},"content":{"rendered":"

So you got into Web Based Animations or Games (using that HTML5 thingie) and chances are high that you’re relying on setInterval<\/code>, setTimeout<\/code> or even better – requestAnimationFrame<\/a> to reflow and repaint your frames (fancy terms for rendering each animation frame). Precisely, you’re basing your animations or game mechanics on the frame rate. There’s nothing wrong with that, but let me show you a more sophisticated approach which can actually enhance all sorts of user experience – time based animations<\/em>.
\n<\/p>\n

Frame based animations<\/h2>\n

I’m assuming you already know about frames. Every animation occurs over a set of frames per second creating the illusion of motion.<\/p>\n

When I say frame based animations, what I basically mean is that for instance, you might be animating your objects based on frames, i.e., whenever a frame is rendered, the object’s position is changed by some value without taking anything else into consideration. By “anything else” I am mostly refering to the delay between each frames or simply the frame rate. For example, you might be moving an object by 5px<\/code> to the right in each frame. Take a look at this piece of code and output:<\/p>\n

<\/pre>\n
\r\nfunction move() {\r\n\tctx.clearRect(0, 0, window_width, window_height);\r\n\tvar c = circle;\r\n\r\n\t\/\/ Drawing circle and increment its x-position in each frame\r\n\tc.draw();\r\n\tc.x += 5;\r\n\t\r\n\t\/\/ Put the circle back at starting point if it goes out \r\n\t\/\/ of the viewport\r\n\tif(c.x - c.radius > window_width)\r\n\t\tc.x = -c.radius;\r\n}\r\n<\/pre>\n

A circle moving 5 pixels to the right per frame regardless of the frame rate. So if your frame rate is 60, circle moves by 60×5 = 300 pixels. If your CPU is busy or you view the animation on a low end mobile where the FPS is 30 then the circle moves by 150pixels. For some crazy reason if the FPS is 1, the movement observed is 5px. I’m sure you’ve started to think of the issues by now.<\/p>\n

Look how this animation plays on my 1GHz single core processor phone and my laptop.<\/p>\n