Game Development Reference
In-Depth Information
Note If you download example code or open source code and related assets, you may find naming
conventions for files similar to those used in this chapter. These naming conventions may seem arbitrary,
but they may be programmatically based. Be sure to analyze any new code for the type of trick used here.
Renaming files might seem harmless, but it could break more than you thought.
In a SpriteSheet instance, you have to load the image as you did before, and you have to store
some information about the sprite sheet that it represents. First you load the image and store a
reference to it in the SpriteSheet instance:
Game._spritesStillLoading += 1;
Game._totalSprites += 1;
this._image = new Image();
this._image.src = imageName;
this._image.onload = function () {
Game._spritesStillLoading -= 1;
};
This code first sets two status variables in the Game object so you can keep track of how many sprites
are still loading and how many sprites there are in total. Then you create an Image instance, set its
source, and define the onload event handler, very similar to what you did for the previous games.
You also need to store the number of rows and columns in the sprite sheet. You extract this
information from the file name, but let's set both of these things to 1 by default:
this._sheetColumns = 1;
this._sheetRows = 1;
To retrieve the actual values for these variables, you need to extract them from the string that is
passed as a parameter to the constructor. JavaScript has a very handy method called split that
splits a string into little pieces. As a parameter, the split method takes a delimiter character, and it
returns an array of strings. Here are a few examples of what split can do:
var s1 = "abcabcabc";
var s2 = "spring,summer,autumn,winter";
var s3 = "game";
var result = s1.split('c'); /* result now contains a 3 item array,
["ab", "ab", "ab"] */
result = s2.split(','); /* result now contains a 4 item array,
["spring", "summer", "autumn", "winter"] */
result = s2.split(','); /* result now contains a 1 item array, ["game"] */
 
Search WWH ::




Custom Search