Jump to content

How to load sprite data from a JSON file?


Redleg7
 Share

Recommended Posts

I'm still in beginner learning mode, and I'm trying to accomplish certain tasks in little bites.  I've come to the point where I'd like to do something a little more challenging.  My question is how I can add sprite data that is stored in an external file, for example, a JSON file that contains the variable name for the sprite, type of image to load,  and it's location?
 
Task:
- Add sprites based on sprite data that is stored in an external JSON file.
 
Requirement:
- Load external JSON file containing sprite data
- Create sprites that can be viewed/manipulated in the browser.
 
Basically I want to do this:
let blueInfTm1a = game.add.sprite(100, 250, 'blue_inf_tm');
 
but using an external JSON file instead.
 
I'm assuming a JSON file would be appropriate for this situation, besides later on all my sprite data will be stored in an external "scenario" file.  The kind of games I'm interested in developing are traditional military style games, not Command and Conquer, but more like a hex-based board wargame.  Later I will expand the "sprite" data to include other types of attributes such as attack, defend, mobility, etc. factors.  But for now loading a list of units and creating their sprite images in the browser is good enough.
 
I figure initially I can simply point to my scenario file using code, later on, I'd like the user to choose what scenario to load which means using an open file dialog or maybe an HTML link.
 
I didn't find any examples on how to do this.
 
Any help would be greatly appreciated.
 
Thanks.
 
TJ
Link to comment
Share on other sites

It is not very clear what the JSON file contains. Is it a texture atlas (exported from Texture packer ?) ? Is it a custom JSON file ?

What I undertood from your case, is that the JSON is rather custom (with your own properties). So I think, the only way for you is to let Phaser load and parse the json file, and write your own code to "interpret" data in your JSON.

Link to comment
Share on other sites

You're on the right track, the JSON file is just an external representation of a data structure that you would otherwise put in code, the only concern here is that if you stuff that structure into your code then its available immediately whereas any external resources are asynchronous, meaning they take some time to load before they are available to use. The task here is to get to the same point, i.e. consuming the data, thankfully, Phaser actually helps you here.

Check this example http://phaser.io/examples/v2/loader/load-json-file for loading and consuming an external resource.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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