NetClient.js 1.25 KB
Newer Older
1 2 3
import Logger from "../utils/Logger.js";
import Observable from "../utils/Observable.js";

4 5
const DEFAULT_GAME_ROOM = "star_gazer_lab";

6 7 8 9 10
class NetClient extends Observable {

  constructor() {
    super();
  }
11 12

  connect(url) {
13
    this.client = new Colyseus.Client(url);
14 15 16
  }

  joinGame() {
17 18 19 20 21 22 23 24 25 26
    this.client.joinOrCreate(DEFAULT_GAME_ROOM).then(this.onConnect.bind(this))
      .catch(
        this.onError.bind(this));
  }

  sendGazeData(gazeData) {
    this.room.send({
      type: "gaze",
      data: gazeData
    });
27 28 29
  }

  onConnect(room) {
30 31 32 33 34 35 36 37 38 39 40
    Logger.log(`Player ${room.sessionId} joined ${room.name}`, "NetClient");
    this.room = room;
    this.room.onStateChange(this.onUpdate.bind(this));
    this.room.onMessage(this.onMessage.bind(this));
    this.room.onError(this.onError.bind(this));
    this.room.onLeave(this.onLeave.bind(this));
    this.notifyAll({
      type: "connect",
      ownID: this.room.sessionId
    });

41 42 43
  }

  onUpdate(state) {
44 45 46 47
    this.notifyAll({
      type: "stateupdate",
      state: state
    });
48 49 50
  }

  onMessage(message) {
51
    Logger.log("Received new message from server", "NetClient");
52 53 54 55 56 57 58
  }

  onError(error) {
    console.log(error);
  }

  onLeave() {
59
    Logger.log("Local client left room", "NetClient");
60 61 62 63
  }
}

export default NetClient;