メインコンテンツまでスキップ

Photonを使用したリアルタイムマルチプレイヤー

備考

このデモはマッチメイキングを含む完全なプロジェクトです。チュートリアルのプロジェクトにはPhoton SDKとApp IDが含まれていないため、公開されたままでは接続できません。どちらも、ご自身のアカウントでPhotonから入手します。プレイするには、プロジェクトをフォークし、セットアップの手順で両方を追加してください。その後、床をクリックすると移動できます。

Photonは多くのゲームで使われているホスト型のマルチプレイヤーサービスです。Realtime JavaScript SDKはHTML5ゲームで動作するので、独自のサーバーを動かさずにPlayCanvasで使用できます。

Photonの無料プランでは、最大20人の同時接続ユーザー(CCU)に対応しています。

学習内容​

  • Photon SDKをPlayCanvasに追加する方法
  • Photonを用いたマルチプレイヤー実装

セットアップ​

PlayCanvasプロジェクト​

チュートリアルプロジェクトをフォークします。シーンには、Light、Plane、Camera、そして Player という名前の赤いカプセルがあります。

Tutorial Project

プロジェクトには、このチュートリアルで完成する2つのスクリプト photon-loadbalancing-playcanvas.mjs と player.mjs も含まれています。手順に沿って自分で書く場合は、先にフォークからこれらを削除してください。完成したプロジェクトをそのまま動かす場合は、以下の手順でSDKとApp IDを追加してください。

Photonアカウント​

アプリの作成とSDKのダウンロードにはPhotonアカウントが必要です。

こちらからPhotonアカウントを作成してください。

新しいアプリを作成​

ダッシュボードでCreate New Appをクリックします。

Create New App

アプリケーションタイプ、SDK、名前を選択​

以下を入力して、CREATEをクリックします。

  • Application Type: Multiplayer Game
  • Photon SDK: Realtime
  • Application Name: PlayCanvas-Photon、または任意の名前

Create a New Application

App IDをコピー​

新しいアプリがアプリ一覧に表示されます。App IDをクリックすると全体が表示されるので、コピーしてください。後で必要になります。

App ID

SDKをダウンロード​

PhotonのRealtime JavaScriptクライアントはVoice JavaScript SDKに含まれています。このSDKにはVoiceとChatのクライアントも含まれています。ダウンロードにはサインインが必要です。

ダッシュボードでSDKSをクリック​

SDKs

Voice JavaScriptを選択​

JavaScriptフィルターをクリックし、Voice JavaScriptのカードをクリックします。

JavaScript SDK

DOWNLOADをクリック​

Download SDK

SDKを解凍​

SDKはZIP形式でダウンロードされます。解凍してください: photon-voice-javascript-sdk_vX-X-X-X → lib → photon.min.js。このファイルがRealtimeクライアントです。lib内の他のファイルはVoiceを追加するもので、このチュートリアルでは使用しません。

SDKのインポート​

ダウンロードしたSDKをPlayCanvasエディターにインポートします。

エディターにSDKをアップロード​

Upload SDK

photon.min.jsをエディターのAssetsパネルにドラッグ&ドロップしてください。

Loading Typeは「Asset」のまま​

Loading Type

Loading TypeはAssetのまま、Preloadはチェックしたままにしてください。どちらもアップロード直後の設定です。こうすると、エンジンはどのスクリプトのinitializeよりも前にSDKを読み込み、SDKがグローバルなPhotonオブジェクトを定義します。Before Engineは選ばないでください。ESMスクリプトを使うプロジェクトでは、LauncherがBefore EngineのスクリプトをJavaScriptモジュールとして読み込むため、Photonがグローバルにならず、スクリプトから見つけられません。

マルチプレイヤー実装​

マルチプレイヤー実装では、以下の機能を実行します。

  1. リアルタイム通信と負荷分散のためにPhotonクラスを使用
  2. Photonマスターサーバに接続
  3. ルームの作成または参加
  4. 他のプレイヤーの動作と移動の同期

APIリファレンスと用語集は、Photonのサイトで利用可能です。

PlayCanvasでPhotonを使用​

PlayCanvasからPhotonをインスタンス化するクラスを生成​

Photonを初期化するために、photon-loadbalancing-playcanvas.mjs(Classicスクリプトの場合は photon-loadbalancing-playcanvas.js)というスクリプトアセットを作成します。

import { Script } from 'playcanvas';

/** @enum {string} */
const Region = {
'Select Region': 'default',
'Asia, Singapore': 'asia',
'Australia, Melbourne': 'au',
'Canada, East Montreal': 'cae',
'Chinese Mainland (See Instructions) Shanghai': 'cn',
'Europe, Amsterdam': 'eu',
'India, Chennai': 'in',
'Japan, Tokyo': 'jp',
'Russia Moscow': 'ru',
'Russia, East Khabarovsk': 'rue',
'South Africa Johannesburg': 'za',
'South America, Sao Paulo': 'sa',
'South Korea, Seoul': 'kr',
'Turkey Istanbul': 'tr',
'USA, East Washington': 'us',
'USA, West San José': 'usw'
};

export class PhotonLoadBalancingPlayCanvas extends Script {
static scriptName = 'photonLoadBalancingPlayCanvas';

/**
* The App ID of your Photon application.
*
* @attribute
* @title App Id
* @type {string}
*/
appId = '';

/**
* Clients can only play with clients that use the same version.
*
* @attribute
* @title App Version
* @type {string}
*/
appVersion = '1.0';

/**
* Connect with secure WebSockets.
*
* @attribute
* @title Wss
* @type {boolean}
*/
wss = true;

/**
* Photon Cloud has servers in several regions, distributed across multiple hosting centers over the world. You can choose optimized region for you.
*
* @attribute
* @title Region
* @type {Region}
*/
region = Region['Japan, Tokyo'];

initialize() {
// The Photon SDK must be in the project, preloaded as an asset
if (!window.Photon) {
console.error('Photon is not defined. Add the Photon Realtime JavaScript SDK to the project: https://developer.playcanvas.com/tutorials/real-time-multiplayer-photon/');
return;
}

// Photon Settings
this.loadBalancingClient = new Photon.LoadBalancing.LoadBalancingClient(this.wss ? 1 : 0, this.appId, this.appVersion);
}
}
  • Photon.LoadBalancing.LoadBalancingClient このクラスには、リアルタイム通信のためのPhoton SDKの多くの機能が含まれています。
  • window.Photon SDKはグローバルな Photon オブジェクトを定義します。ESMスクリプトでは、SDKがない場合、エラーを投げる代わりにエラーをログに出力して処理を止めます。

Root entityのスクリプトを設定する​

エディタで photon-loadbalancing-playcanvas スクリプトをRootエンティティに添付します。

Root Entity - Inspector

スクリプト属性にAppIdを貼り付ける​

スクリプト属性にAppIdを入力してください。

Script Attributes

this.loadBalancingClient = new Photon.LoadBalancing.LoadBalancingClient( this.wss ? 1 : 0, this.appId, this.appVersion );
  • wss WebSocketを介した安全な接続。
  • appId アプリケーション識別子の値。
  • appVersion バージョニングに使用されます。異なるバージョンは互いに接続できません。

マスターサーバに接続する​

connectToRegionMaster を使用してマスターサーバに接続する​

initialize() {
// The Photon SDK must be in the project, preloaded as an asset
if (!window.Photon) {
console.error('Photon is not defined. Add the Photon Realtime JavaScript SDK to the project: https://developer.playcanvas.com/tutorials/real-time-multiplayer-photon/');
return;
}

// Photon Settings
this.loadBalancingClient = new Photon.LoadBalancing.LoadBalancingClient(this.wss ? 1 : 0, this.appId, this.appVersion);

// Connect to the master server
if (!this.loadBalancingClient.isInLobby()) {
this.loadBalancingClient.connectToRegionMaster(this.region);
}
}
  • connectToRegionMaster 指定されたリージョンのマスターサーバに接続します。
  • this.region リージョンを設定するために使用されます。

connectToRegionMaster を実行してロビーに接続できた場合はJoinedLobbyがログに表示されます。

Console Log

ルームの作成または参加​

ロビーへの接続が行われた場合は、onRoomList 関数が呼び出されます。

joinRandomOrCreateRoom は、ルームが存在すればランダムなルームに参加し、存在しなければ新しいルームを作成します。

initialize() {
// The Photon SDK must be in the project, preloaded as an asset
if (!window.Photon) {
console.error('Photon is not defined. Add the Photon Realtime JavaScript SDK to the project: https://developer.playcanvas.com/tutorials/real-time-multiplayer-photon/');
return;
}

// Photon Settings
this.loadBalancingClient = new Photon.LoadBalancing.LoadBalancingClient(this.wss ? 1 : 0, this.appId, this.appVersion);

// Connect to the master server
if (!this.loadBalancingClient.isInLobby()) {
this.loadBalancingClient.connectToRegionMaster(this.region);
}

// Added
// Photon calls these methods on the client. Forward them to this script.
this.loadBalancingClient.onRoomList = rooms => this.onRoomList(rooms);
this.loadBalancingClient.onJoinRoom = createdByMe => this.onJoinRoom(createdByMe);
}

onRoomList(rooms) {
this.loadBalancingClient.joinRandomOrCreateRoom();
}

onJoinRoom(createdByMe) {
console.log('Joined the room.');
}
  • onRoomList(rooms) ロビー内のルームのリスト
  • joinRandomOrCreateRoom(options, createRoomName, createOptions) ランダムにルームに参加します。ルームが存在しない場合は新しいルームが作成されます。
  • onJoinRoom ルームに参加したときに呼び出されます。

Photonはこれらのハンドラーをクライアントのメソッドとして呼び出します。ESMスクリプトでは、各アロー関数が呼び出しをスクリプト自身のメソッドに転送します。そのメソッド内では this はスクリプトで、クライアントは this.loadBalancingClient です。Classicスクリプトは代わりに自身のメソッドをクライアントに直接割り当てるので、メソッド内の this はクライアントになります。Classicスクリプトが loadBalancingClient.app を設定しているのはそのためで、ハンドラーから this.app でアプリケーションにアクセスできるようにしています。

参加と退出​

プレイヤーが部屋に参加すると、他のプレイヤーと同期されます。 onActorJoin と onActorLeave を使用します。

import { Script, Entity } from 'playcanvas';

// ...

initialize() {
// The Photon SDK must be in the project, preloaded as an asset
if (!window.Photon) {
console.error('Photon is not defined. Add the Photon Realtime JavaScript SDK to the project: https://developer.playcanvas.com/tutorials/real-time-multiplayer-photon/');
return;
}

// Photon Settings
this.loadBalancingClient = new Photon.LoadBalancing.LoadBalancingClient(this.wss ? 1 : 0, this.appId, this.appVersion);

// Connect to the master server
if (!this.loadBalancingClient.isInLobby()) {
this.loadBalancingClient.connectToRegionMaster(this.region);
}

// Photon calls these methods on the client. Forward them to this script.
this.loadBalancingClient.onRoomList = rooms => this.onRoomList(rooms);
this.loadBalancingClient.onJoinRoom = createdByMe => this.onJoinRoom(createdByMe);

// Added
this.loadBalancingClient.onActorJoin = actor => this.onActorJoin(actor);
this.loadBalancingClient.onActorLeave = actor => this.onActorLeave(actor);
}

onRoomList(rooms) {
this.loadBalancingClient.joinRandomOrCreateRoom();
}

onJoinRoom(createdByMe) {
console.log('Joined the room.');
}

onActorJoin(actor) {
if (actor.isLocal) return;

// Name the entity after the actor number, so we can find it again
const otherPlayer = new Entity(String(actor.actorNr));
otherPlayer.addComponent('render', { type: 'capsule' });
otherPlayer.setLocalPosition(0, 1, 0);
this.app.root.children[0].addChild(otherPlayer);
}

onActorLeave(actor) {
const otherPlayer = this.app.root.findByName(String(actor.actorNr));
if (actor.isLocal || !otherPlayer) return;
otherPlayer.destroy();
}

Actor

  • actor は name, actorNr , isLocal , userId を含みます。
  • onActorJoin 新しいユーザーが接続すると、参加したアクターを取得できます。
  • onActorLeave ユーザーが切断されると、切断されたアクターを取得できます。

成功した場合、プレイヤーが参加したときにエンティティが追加されます。

Console log - Actors

プレイヤーの移動​

キャラクターの移動用に player.mjs(Classicスクリプトの場合は player.js)という新しいスクリプトを作成し、Playerエンティティに添付します。

import { Script, Vec3, KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN } from 'playcanvas';

export class Player extends Script {
static scriptName = 'player';

update(dt) {
const pos = new Vec3(0, 0, 0);
if (this.app.keyboard.isPressed(KEY_LEFT)) {
pos.x = -dt;
}
if (this.app.keyboard.isPressed(KEY_RIGHT)) {
pos.x = dt;
}
if (this.app.keyboard.isPressed(KEY_UP)) {
pos.z = -dt;
}
if (this.app.keyboard.isPressed(KEY_DOWN)) {
pos.z = dt;
}

if (!pos.equals(Vec3.ZERO)) {
this.entity.translate(pos);
}
}
}
  • this.app.keyboard.isPressed: キーボードが押されているかどうかを確認します。

他のプレイヤーを同期する​

他のプレーヤーの位置を同期するために、raiseEvent と onEvent を使用します。

raiseEvent を使用した位置の同期​

import { Script, Entity } from 'playcanvas';

/** @enum {string} */
const Region = {
'Select Region': 'default',
'Asia, Singapore': 'asia',
'Australia, Melbourne': 'au',
'Canada, East Montreal': 'cae',
'Chinese Mainland (See Instructions) Shanghai': 'cn',
'Europe, Amsterdam': 'eu',
'India, Chennai': 'in',
'Japan, Tokyo': 'jp',
'Russia Moscow': 'ru',
'Russia, East Khabarovsk': 'rue',
'South Africa Johannesburg': 'za',
'South America, Sao Paulo': 'sa',
'South Korea, Seoul': 'kr',
'Turkey Istanbul': 'tr',
'USA, East Washington': 'us',
'USA, West San José': 'usw'
};

export class PhotonLoadBalancingPlayCanvas extends Script {
static scriptName = 'photonLoadBalancingPlayCanvas';

/**
* The App ID of your Photon application.
*
* @attribute
* @title App Id
* @type {string}
*/
appId = '';

/**
* Clients can only play with clients that use the same version.
*
* @attribute
* @title App Version
* @type {string}
*/
appVersion = '1.0';

/**
* Connect with secure WebSockets.
*
* @attribute
* @title Wss
* @type {boolean}
*/
wss = true;

/**
* Photon Cloud has servers in several regions, distributed across multiple hosting centers over the world. You can choose optimized region for you.
*
* @attribute
* @title Region
* @type {Region}
*/
region = Region['Japan, Tokyo'];

initialize() {
// The Photon SDK must be in the project, preloaded as an asset
if (!window.Photon) {
console.error('Photon is not defined. Add the Photon Realtime JavaScript SDK to the project: https://developer.playcanvas.com/tutorials/real-time-multiplayer-photon/');
return;
}

// Photon Settings
this.loadBalancingClient = new Photon.LoadBalancing.LoadBalancingClient(this.wss ? 1 : 0, this.appId, this.appVersion);

// Connect to the master server
if (!this.loadBalancingClient.isInLobby()) {
this.loadBalancingClient.connectToRegionMaster(this.region);
}

// Photon calls these methods on the client. Forward them to this script.
this.loadBalancingClient.onRoomList = rooms => this.onRoomList(rooms);
this.loadBalancingClient.onJoinRoom = createdByMe => this.onJoinRoom(createdByMe);
this.loadBalancingClient.onActorJoin = actor => this.onActorJoin(actor);
this.loadBalancingClient.onActorLeave = actor => this.onActorLeave(actor);
this.loadBalancingClient.onEvent = (code, content, actorNr) => this.onEvent(code, content, actorNr);

this.app.on('loadbalancing:sendPlayerPosition', this.sendPlayerPosition, this);
}

onRoomList(rooms) {
this.loadBalancingClient.joinRandomOrCreateRoom();
}

onJoinRoom(createdByMe) {
// Create an entity for each player who was already in the room
this.loadBalancingClient.myRoomActorsArray().forEach((actor) => {
if (actor.isLocal) return;
this.createOtherPlayerEntity(actor);
});
}

onActorJoin(actor) {
if (actor.isLocal) return;
this.createOtherPlayerEntity(actor);

// Tell the new player where our player is
const { x, y, z } = this.app.root.findByName('Player').getLocalPosition();
this.sendPlayerPosition({ x, y, z });
}

onActorLeave(actor) {
const otherPlayer = this.app.root.findByName(String(actor.actorNr));
if (actor.isLocal || !otherPlayer) return;
otherPlayer.destroy();
}

createOtherPlayerEntity(actor) {
// Name the entity after the actor number, so we can find it again
const entity = new Entity(String(actor.actorNr));
entity.addComponent('render', { type: 'capsule' });
entity.setLocalPosition(0, 1, 0);
this.app.root.children[0].addChild(entity);
}

sendPlayerPosition(position) {
if (!this.loadBalancingClient?.isJoinedToRoom()) return;
this.loadBalancingClient.raiseEvent(1, { position });
}

onEvent(code, content, actorNr) {
switch (code) {
case 1: {
const otherPlayer = this.app.root.findByName(String(actorNr));
if (otherPlayer) {
const { x, y, z } = content.position;
otherPlayer.setLocalPosition(x, y, z);
}
break;
}
}
}
}
  • raiseEvent(eventCode,data, options) eventCode と data を送信します。
  • onEvent(code, content, actorNr) データを受信します。actorNr と eventCode を含みます。
  • isJoinedToRoom() ESMスクリプトは、ルームに参加してからイベントを送信します。

プレイヤーが移動した際にイベントを発火するよう変更​

import { Script, Vec3, KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN } from 'playcanvas';

export class Player extends Script {
static scriptName = 'player';

update(dt) {
const pos = new Vec3(0, 0, 0);
if (this.app.keyboard.isPressed(KEY_LEFT)) {
pos.x = -dt;
}
if (this.app.keyboard.isPressed(KEY_RIGHT)) {
pos.x = dt;
}
if (this.app.keyboard.isPressed(KEY_UP)) {
pos.z = -dt;
}
if (this.app.keyboard.isPressed(KEY_DOWN)) {
pos.z = dt;
}

if (!pos.equals(Vec3.ZERO)) {
this.entity.translate(pos);

// Added
// Send the new position to the other players
const { x, y, z } = this.entity.getPosition();
this.app.fire('loadbalancing:sendPlayerPosition', { x, y, z });
}
}
}
  • this.app.fire は、スクリプト間の 通信に使用されます。

完成​

Photonを使用してマルチプレイヤーをプレイできるようになりました!

Photonを使ってルームを作成し、プレイヤーの位置を同期できます。

このプロジェクトはプレイヤー間のシンプルなリアルタイム通信でしたが、マッチメイキングを含むプロジェクトも作成できます。ルームの作成やリスト表示を含む完全なプロジェクトについては、完全なプロジェクトを参照してください。こちらはClassicスクリプトを使用しています。