Organizing message sending/calling room methods.

Hi everyone!

I often have to send messages to the client from some part of the state - usually someplace in the player logic (eg. when the player gets hit). To do this I must pass the room object to the state object which then passes it to the player objects which can then call the room's methods. This always feels a bit hack-ish as I am calling methods from places where they shouldn't be. Is there a way that I can organize things a bit more elegantly or is this the intended way for messages to be sent?

Thanks in advance.

What you could do is pass a callback method to the state during initialisation

In your room:

class MyRoom extends Room<MyState> {

  onCreate() {
    this.setState(new MyState(this.mySuperCallback));
  }

  mySuperCallback = (playerId: string) => {
    this.send(...);
  }
}

And in you state:

class MyState extends Schema {

  private mySuperCallback: (playerId: string) => void;

  constructor(mySuperCallback:  (playerId: string) => void) {
    super();

    this.mySuperCallback = mySuperCallback;
  }

This is how I have done it to broadcast important messages to all players in room when one of them dies, wins...

Also, if you’re creating separate files to keep your code lean, I created a class with a static variable pointing to the room. In the onCreate event of Room, I assign the static room property. Then I can import that class from any file and use the room methods.