There’s another small optimization to do in order to keep your code organized, especially if you are working on a small game which does not require that much images and sounds. At the moment we preload assets in a way we can call “on demand”. When in title screen we needed the sound buttons, we preloaded their images, then when in game state we needed the sounds and the tiles, we preloaded them.
It would be better if we could preload all assets before the game begins, so all code and references to images and sounds can be found in a single place. That’s why are going to create a new state called PreloadAssets which will handle all preloading process, freeing other states from having a preload method.
Obviously this newly created state will be the first the game will execute, to ensure all assets have been preloaded before we launch the game itself with TitleScreen state.
1 2 3 4 5 6 7 |
game.state.add("PreloadAssets", preloadAssets); game.state.add("TitleScreen", titleScreen); game.state.add("PlayGame", playGame); game.state.add("GameOver", gameOver); highScore = localStorage.getItem(localStorageName) == null ? 0 : localStorage.getItem(localStorageName); game.state.start("PreloadAssets"); |
The code of PreloadAssets is just a cut/paste of the code of the preload methods in PlayGame and TitleScreen states:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
var preloadAssets = function(game) {} preloadAssets.prototype = { preload: function() { game.load.spritesheet( "tiles", "assets/sprites/tiles.png", tileSize, tileSize ); game.load.audio( "select", ["assets/sounds/select.mp3", "assets/sounds/select.ogg"] ); game.load.audio( "right", ["assets/sounds/right.mp3", "assets/sounds/right.ogg"] ); game.load.audio( "wrong", ["assets/sounds/wrong.mp3", "assets/sounds/wrong.ogg"] ); game.load.spritesheet( "soundicons", "assets/sprites/soundicons.png", 80, 80 ); }, create: function() { game.state.start("TitleScreen"); } } |
As you can see I only copied the content of the old preload methods – which you will have to remove now – and in create method, once all assets have been loaded, I launch TitleScreen state, starting the game.
Download Source
File: creating-preloader-state.zip