はじめに
- 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つしかない場合での簡易的な実装になります。
キャラ素材が複雑でテクスチャが複数である場合などは、都度実装を考える必要があります。