PlayCanvasでJavasScriptのクラス構文を使って開発をする


PlayCanvasとは?

PlayCanvasは、インタラクティブなウェブコンテンツ用のビジュアル開発プラットフォームです。作成するツールとウェブアプリは、どちらもHTML5を使用しています。 プラットフォームはウェブでホストされているため、インストールするものは何もなく、対応されているウェブブラウザを実行する任意のデバイスからアクセスできます。

PlayCanvas ユーザーマニュアルより

PlayCanvasのpcオブジェクトの拡張について

PlayCanvasで拡張機能を作る場合にはよくpc.extendを使用して拡張を行います。
Spineのプラグインなどもその方法で作られています。

PlayCanvasのGUIからスクリプトを作ると初期状態ではこのような状態でスクリプトが生成され、スクリプトが適用されます。

スクリプト作成をした初期状態

rotate.js
var Rotate = pc.createScript('rotate');

Rotate.prototype.initialize = function() {
};
Rotate.prototype.update = function(dt) {
};

回転をアップデート毎に行うスクリプト

rotate.js
var Rotate = pc.createScript('rotate');

Rotate.prototype.initialize = function() {
};
Rotate.prototype.update = function(dt) {
    this.entity.rotate(0,1,0)
};

今回作ったスクリプトを事前に読み込んでおくとおくと以下の流れでScriptを記述することができるようになります。

rotate.js
const registerScript = (App, attributeses) => {
  const name = App.name.toLowerCase();
  const app = pc.createScript(name);
  if (attributeses !== undefined) {
    const attributes = Object.values(attributeses);
    for (let attr of attributes) {
      Object.entries(attr).forEach(item => {
        app.attributes.add(item[0], item[1]);
      });
    }
  }
  Object.setPrototypeOf(app.prototype, App.prototype);
};

class Rotate {
  initialize() {}

  update() {
    this.entity.rotate(0, 1, 0);
  }
}

registerScript(Rotate);

//PlayCanvasエディター上にregisterScriptのコードをコピーした場合は pc.registerScript(Rotate)で登録ができます。
// External Scriptsから読み込んだ場合は registerScriptとして呼び出します。

とすると回らせることができます。

補足

属性(アトリビュート)を追加することでGUIから色々値を変更できるようになります。

const registerScript = (App, attributeses) => {
  const name = App.name.toLowerCase();
  const app = pc.createScript(name);
  if (attributeses !== undefined) {
    const attributes = Object.values(attributeses);
    for (let attr of attributes) {
      Object.entries(attr).forEach(item => {
        app.attributes.add(item[0], item[1]);
      });
    }
  }
  Object.setPrototypeOf(app.prototype, App.prototype);
};

class Rotate {
  initialize() {}

  update() {
    this.entity.rotate(this.x, this.y, this.z);
  }
}
const attributeses = [
  {
    x: {
      type: "number",
      default: 0
    },
    y: {
      type: "number",
      default: 0
    },
    z: {
      type: "number",
      default: 0
    }
  }
];

registerScript(Rotate, attributeses);


PlayCanvas開発で参考になりそうな記事の一覧です。


入門


その他関連
- PlayCanvasタグの付いた記事一覧

PlayCanvasのユーザー会のSlackを作りました!

少しでも興味がありましたら、ユーザー同士で解決・PlayCanvasを推進するためのSlackを作りましたので、もしよろしければご参加ください!

日本PlayCanvasユーザー会 - Slack