1
0

More than 3 years have passed since last update.

[PlayCanvas] Spineデータを外部から取得して、再生する

Last updated at Posted at 2021-03-22

はじめに

  • DMM GAMESにあるようなブラウザゲームを作りたい。
  • キャラが増える度に インポート→ビルド をするのは手間。
  • とりあえず公式プラグインを使用して実装する。

急遽必要になった実装なので、備忘録的に。

アセット取得

Spineアニメーションを構成するSkeleton, Atlas, Textureを取得します。
外部リソースを使用するため、assets.loadFromUrl()を使用してアセットの読み込み、作成をします。

Skeleton

SkeletonはJson形式なのでpc.ASSET_JSONで取得できます。

const url = '';
this.app.assets.loadFromUrl(url, pc.ASSET_JSON, (err, asset)=>{
    this.skeleton = asset;
});

Atlas

Atlasはassets.loadFromUrl()がサポートする形式ではないので、ファイル拡張子をtxtに書き換える必要がある。
その上で、取得時は第2引数の型にpc.ASSET_TEXTを指定します。

const url = '';
this.app.assets.loadFromUrl(url, pc.ASSET_TEXT, (err, asset)=>{
    this.atlas = asset;
});

Texture

pc.ASSET_TEXTUREで取得できます。

const url = '';
this.app.assets.loadFromUrl(url, pc.ASSET_TEXTURE, (err, asset)=>{
    this.texture = asset;
});

スクリプトにセット、再生

取得した各アセットを使用してアニメーションを再生します。
再生方法などは調べると出てくるので、ここではセットだけ。

this.entity.script.create('spine', {
    attributes: {
        atlas: this.atlas,
        skeleton: this.skeleton,
        textures: [this.texture],
    }
});

const anim_name = '';
this.entity.spine.state.setAnimation(0, anim_name, false);

まとめ

ここまでの処理をひとまとめにしてみます。

var ExternalSpineAsset = pc.createScript('externalSpineAsset');

ExternalSpineAsset.attribute.add('status', {type: 'number', default: 0});

ExternalSpineAsset.prototype.initialize = function() {
    this.atlas = null;
    this.skeleton = null;
    this.texture = null;

    this.on('attr:status', this.onUpdateStatus, this);

    this.app.assets.loadFromUrl('url', pc.ASSET_JSON, this.onLoadAtlas);
    this.app.assets.loadFromUrl('url', pc.ASSET_TEXT, this.onLoadSkeleton);
    this.app.assets.loadFromUrl('url', pc.ASSET_TEXTURE, this.onLoadTexture);
};

ExternalSpineAsset.prototype.onLoadAtlas = function(err, asset) {
    this.atlas = asset;
    this.status |= 1;
};
ExternalSpineAsset.prototype.onLoadSkeleton = function(err, asset) {
    this.skeleton = asset;
    this.status |= (1 << 1);
};
ExternalSpineAsset.prototype.onLoadTexture = function(err, asset) {
    this.texture = asset;
    this.status |= (1 << 2);
};

ExternalSpineAsset.prototype.onUpdateStatus = function(value, prev) {
    if( value === 7 ){
        this.entity.script.create('spine', {
            attributes: {
                atlas: this.atlas,
                skeleton: this.skeleton,
                textures: [ this.texture ]
            }
        });
    }
};

おわりに

各アセットが1つしかない場合での簡易的な実装になります。
キャラ素材が複雑でテクスチャが複数である場合などは、都度実装を考える必要があります。

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