Static Functions in Phaser 3 Class Extending Scene

Hi,

In my game I have extended the scene class and the aim is to create a multiplayer game so I am running my express server which emits an event to the individual clients when it has paired that player with another player. Then I want to call a function which will create the player. I am wondering if it is possible or the only way is to put the code directly into the event for the socket?

The socket event (inside the create function) looks like :

  var paired = false;

  this.socket.on('pair', function (pair) {
    if(!paired) {
        alert(JSON.stringify(pair));
        this.createPlayer(pair);
    }
  });

Then the create player function looks like:

  createPlayer: function (player) {
    if(player.playerNo == 1) {
      // create the player sprite
    else { 
        //create the player 2 sprite
    }
   },

If this isn’t possible and I have to create the players from within the socket event, then how do I scope player1 and player2 to the scene class? Do I have to have something like:

this.player1;
this.player2;
var player1 = this.player1;
var player2 = this.player2;

And then set the player 1 and 2 that I create to the variables? What is the correct way to scope the objects you want available to the whole scene?

1 Like

What will happen when you have 1k of users? I think you’re painting yourself into a corner.

The server will limit the connections so it won’t admit new users when that limit is reached until someone else drops off. That isn’t what I am asking though.

If I understand you correctly then it is possible to call your Scene’s createPlayer() method from the callback of the socket event.

I am guessing it is not working for you in this code:

Because you are using an anonymous function where this is no longer the Scene when it executes.

You can use an arrow function like this instead:

this.socket.on('pair', pair => {
  // other code...
  this.createPlayer(pair)
})

Hi Supertommy,

Many thanks, it looks like I am able to get it to work by setting a variable to the scene. I will try this way that you suggest in the future.

1 Like

@Skeletron amazing