LoginSignup
1
0

More than 1 year has passed since last update.

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

Last updated at Posted at 2019-08-28

2023/03/23 こちらは不要となりました。

class Class  extends pc.ScriptType {
  initialize(){}
  update(){}
}

pc.registerScript('Class', Class);

こちらで記述できるようになりました。

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);

s3l9i-9w0o6

PlayCanvas開発で参考になりそうな記事の一覧です。 入門 応用 その他の記事はこちらになります。 その他関連 - [PlayCanvasタグの付いた記事一覧](https://qiita.com/tags/playcanvas)

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

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

日本PlayCanvasユーザー会 - Slack

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0