GAZ082 Posted November 11, 2018 Share Posted November 11, 2018 Hey guys I've got something like this to load data from backed and send it to my phaser object: import { makeGame } from '/game.js'; function loadData() { let mapSize = 64; let tileSize = 4; let xhttp = new XMLHttpRequest(); xhttp.open( 'GET', 'http://localhost:5000/map?size=' + mapSize + '&tileSize=' + tileSize + '&img=0', true ); xhttp.send(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { let map = JSON.parse(xhttp.responseText); let empire = makeGame(map, mapSize, tileSize); //console.log(empire) returns undefined. } }; } function init(cb) { console.log(cb()); //returns undefined. } window.onload = function() { init(loadData); }; Now i'm trying to make some UI in standard JS+CSS and i need to access the game properties (add/destroy images, stuff like that) and cant get a object outside the main game loop to be the created Phaser.game. How can i do that? As you can tell, JS is not my forte :P Thanks! Link to comment Share on other sites More sharing options...
Telinc1 Posted November 11, 2018 Share Posted November 11, 2018 What does your `makeGame` method do? If it just instantiates a `Phaser.Game`, you should be able to return it normally, at which point it'll be set as the `empire` variable. Note that, even if you return your game instance from `makeGame`, it won't be returned from the `loadData` method because an XMLHttpRequest is asynchronous and calls your `onreadystatechange` handler only after it completes. If you want your game instance in the `init` function, you should pass a callback to the `loadData` function and call it with the game from the `onreadystatechange` handler. Alternatively, you could research Promises. Link to comment Share on other sites More sharing options...
GAZ082 Posted November 11, 2018 Author Share Posted November 11, 2018 Thanks man, yes, i'm already researching about promises, fetch, etc. and got what you mean. Link to comment Share on other sites More sharing options...
samme Posted November 11, 2018 Share Posted November 11, 2018 Could you just put it in a scene? function preload() { let mapSize = 64; let tileSize = 4; this.load.json('map', 'http://localhost:5000/map?size=' + mapSize + '&tileSize=' + tileSize + '&img=0'); } function create() { let map = this.cache.json.get('map'); let empire = makeGame(map, mapSize, tileSize); // … } Link to comment Share on other sites More sharing options...
Recommended Posts