拒絕玩家加入房間

您可以在調用 onAuth()onJoin() 方法時展示一個錯誤提示來拒絕玩家接入.

至於何時執行拒絕操作則取決於您的用例.

下面這個例子是驗證 @colyseus/social 身份認證令牌, 然後通過用戶 id 獲取相關聯的 Hero 記錄.

export class BattleRoom extends Room {

  onCreate(options) {
    this.levelRequired = 10;
  }

  async onAuth(client, options) {
    const userId = verifyToken(options.token)._id;
    const hero = await Hero.findOne({ userId });

    if (!hero) {
      throw new Error("'Hero' not found in the database!");

    } else if (hero.level < this.levelRequired) {
      throw new Error("player do not have the level required to be on this room.");

    }

    return hero;
  }

}

客戶端在嘗試加入房間時會收到錯誤提示:

client.joinOrCreate("battle", {}).then(room => {
  // ...
}).catch(e => {
  console.log(e) // "數據庫沒找到 'Hero' 數據!"
})

Back to top