Next2D Frameworkのシーン遷移時には複数のcallbackのタイミングがあります。
callbackに必要な関数
callback
の実行は、指定したクラスをnew
演算子の第一引数にデータをセットし、execute
関数をコールします。各クラスのconstructor
で必要なデータを受け取り、execute
関数で任意の処理を行うイメージです。callback
設定は配列も可能です。配列にする事で複数のcallback
を設定できます。
事前技術共有
src/model
に設置したクラスはディレクトリ階層を.
として分解され、next2d.fw.packages
に登録されます。
routingのリクエスト終了時
routingのリクエスト終了毎にcallbackがコールされます。
受け取ったレスポンスデータをconstructor
で受け取り、execute
関数で事後処理を行う事ができます。
routing.jsonの設定例
src/model
にcallback
というディレクトリを追加し、src/model/callback
にSample.js
っというクラウを作成した場合、下記のようにアクセスが可能です。
{
"top": {
"requests": [
{
"type": "json",
"path": "{{ api.endPoint }}api/top.json",
"name": "TopText",
"callback": ["callback.Sample"]
}
]
}
}
gotoViewの終了時
gotoViewの処理が全て終了タイミングでコールされます。
config.jsonの設定例
src/model
にcallback
というディレクトリを追加し、src/model/callback
にBackground.js
っというクラウを作成した場合、下記のようにアクセスが可能です。
{
...中略
"all": {
"gotoView": {
"callback": ["callback.Background"]
}
}
}
今回はシーン移動毎に背後にグラデーションの背景を生成するサンプルを記載します。
/**
* @class
* @extends {next2d.fw.Model}
*/
export class Background extends next2d.fw.Model
{
/**
* @constructor
* @public
*/
constructor()
{
super();
if (!Background.shape) {
const { Shape, GradientType } = next2d.display;
const { Matrix } = next2d.geom;
const shape = new Shape();
shape.name = "background";
const width = this.config.stage.width;
const height = this.config.stage.height;
const matrix = new Matrix();
matrix.createGradientBox(width, height, Math.PI / 2);
shape
.graphics
.beginGradientFill(
GradientType.LINEAR,
["#1461A0", "#ffffff"],
[0.6, 1],
[0, 255],
matrix
)
.drawRect(0, 0, width, height)
.endFill();
Background.shape = shape;
}
}
/**
* @return {void}
* @public
*/
execute ()
{
const { Event } = next2d.events;
const stage = this.context.root.stage;
if (!stage.hasEventListener(Event.RESIZE)) {
stage.addEventListener(Event.RESIZE, function ()
{
this._$createShape();
}.bind(this));
}
this._$createShape();
}
/**
* @return {void}
* @private
*/
_$createShape ()
{
const view = this.context.view;
if (!view) {
return ;
}
const root = this.context.root;
const width = this.config.stage.width;
const height = this.config.stage.height;
let shape = view.getChildByName("background");
if (!shape) {
shape = view.addChildAt(Background.shape, 0);
}
const player = root.stage.player;
const tx = player.x;
if (tx) {
const scaleX = player.scaleX;
shape.scaleX = (width + tx * 2 / scaleX) / width;
shape.x = -tx / scaleX;
}
const ty = player.y;
if (ty) {
const scaleY = player.scaleY;
shape.scaleY = (height + ty * 2 / scaleY) / height;
shape.y = -ty / scaleY;
}
}
}
/**
* @type {next2d.display.Shape}
* @default null
* @static
*/
Background.shape = null;
この様にcallbackを利用する事で、多様な処理を事前・事後に行う事が可能です。
明日からは実際にゲームを制作を行えればと思います。