4
\$\begingroup\$

I have made a type to shoot game using HTML5, Javascript and Ruby on Rails.
Here is the link for the game Tweetraitor

I wanted to make a loader for resources (sounds, images) when the game starts. Currently when the game starts the background image takes time to load and it does not look good. This loader should load all the assets those are used later in the game.

Code for the game is here: Tweetraitor on GitHub

In the current version, all the images are loaded using js in an erb file which controls the game logic. Is there a better way to do this?

\$\endgroup\$
  • \$\begingroup\$ Check this out: thinkpixellab.com/pxloader But it's pure JavaScript. This preloader is used in HTML5 version of Cut the Rope game \$\endgroup\$ – saiy2k Feb 18 '12 at 5:12
3
\$\begingroup\$

I have to admit I have no idea of Ruby and how it's used together with js, but here is how I'd do it with js:

window.onload = function() {
        var sources = {
            resource1: "img/sprite1.png",
            resource2: "img/sprite2.png",
            resource3: "img/sprite3.png"
        };
        loadImages(sources, initGame);  // calls initGame after *all* images have finished loading
    };

    function loadImages(sources, callback) {
        var images = {};
        var loadedImages = 0;
        var numImages = 0;
        for (var src in sources) {
            numImages++;
        }
        for (var src in sources) {
            images[src] = new Image();
            images[src].onload = function(){
                if (++loadedImages >= numImages) {
                    callback(images);
                }
            };
            images[src].src = sources[src];
        }
    } 

    function initGame(images) {
        // some code here...
    }
\$\endgroup\$
  • \$\begingroup\$ Thank you. That's definitely better than what i am doing. \$\endgroup\$ – s2n Feb 18 '12 at 6:25
  • \$\begingroup\$ Note that when there is just one image which doesn't load for some reason, the game will load forever and there will be no error message. So you should also add an .onerror handler to the images you load. \$\endgroup\$ – Philipp Jan 28 '13 at 10:27
  • \$\begingroup\$ Why not just use numImages = sources.length; instead of the for loop ? \$\endgroup\$ – Victor Stoddard Jan 10 '18 at 2:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.