Jump to content

Loading images with variable


Recommended Posts

I'm sure this is something silly but I would appreciate the help.

I'm trying to load an image based on some JSON passed from the server.  I have verified that it is being received from the server properly and am using it to load my game world and tiles.  I cannot, however, get it to do the initial image load.  Cutting out the passing from server it looks like something like:

var loadGame = {};

loadGame = {gameMap : "space", gameSizeX: 2000, gameSizeY: 2000};

then in my load function:


game.load.image(loadGame.gameMap, 'assets/backgrounds/' + loadGame.gameMap +'.jpg');


This always fails and loads the null background instead.  It also fails when I write the path in manually but leave the name as a variable.  It succeeds when i replace the variables with:


game.load.image('space', 'assets/backgrounds/space.jpg');


Finally, just as evidence that my object is in fact working properly, the following works as long as I load the image manually:

game.add.tileSprite(0,0, loadGame.gameSizeX,loadGame.gameSizeY, loadGame.gameMap);
game.world.setBounds(0, 0, loadGame.gameSizeX, loadGame.gameSizeY);

Any assistance you could provide would be greatly appreciated.  I'm doing something stupid, but I can't for the life of me figure it out.


I have run typeof() on the loadGame.gameMap and confirmed that it is a string as well.  Is phaser looking for something other than a string there?



Link to comment
Share on other sites

If the value comes out as null then the problem is simply that your object is not created at the time the preload function runs, OR that it's not available. I.e. isn't in the global scope, so cannot be read by it. Try this: Move the line of code that creates the object to the top of the preload function. I'll put money on it working then.

Link to comment
Share on other sites

Thank you Rich, your instincts were spot on.

I forgot that socket.io runs asynchronously so despite it being first in my code it was not loaded by the time the game pre loads were called.  It was working later just due to having more time for the event listener to trigger and receive the JSON.

If anyone else has this problem I just included the portion that calls the preload:

	var game = new Phaser.Game(1024, 768, Phaser.AUTO, '', { preload: preload, create: create, update: update });

Into the event listener such that it would not load the game until that listener had fired.

Link to comment
Share on other sites


  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Create New...