Javascript game development 4: main loop

In most cases, it’s not enough for a games to paint single frames. Except for point ‘n click or other event based games, we need proper movement through real time rendering. This is done in a loop.
To properly integrate this in our module structure, I created a new module “main”. This module is the center of the game and contains the rendering loop.

Result of this chapter

download chapter

Here’s the source of the main module for now.

window.modules.main = (function($) {
    return {
        //the rendering loop
        loop: (function() {
            var modules = window.modules;
            var objects = window.objects;
             *  call requestAnimationFrame before the execution of the code to smooth the animation              
             *  in 1 / 60 seconds we got back here
            var v = new objects.vector();
            //timestamp as starting point
            var d = / 500;
            //same thing as last chapter
            for(i = d; i < d + 128; i++)
                v.mul(i % 64);
                v.add(new objects.vector(160, 120));
                   (i % 255),
                   (i % 128 + 128),
                   (i % 64 + 192)

The main.loop() method is accessed 60 times a second. HTML5 provides the function “requestAnimationFrame” and is compatible with more than 90 % of browsers used nowadays. Using a modern browser is obviously recommended. Inside the loop I adjusted the parameters of the mathematical drawing function, with the result that it’s starting from different points (with the timestamp).
And now we got a galaxy like animation.

To start the loop, I used the old “loadingcomplete” event. In the index.html.


$(window).on("loadingcomplete", function() {