GAZ082

How to return a Phaser.Game object?

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!

 

 

Share this post


Link to post
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.

Share this post


Link to post
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);
  // …
}

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.