Jump to content

How to return a Phaser.Game object?


GAZ082
 Share

Recommended Posts

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

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

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

 Share

  • Recently Browsing   0 members

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