ゲーム作りは楽しい

なんか書く

CocosCreator Effect classを考える

挨拶

久しぶりの投稿です。 4月から就職しました。(一応ゲームエンジニア)
最近はCocosCreatorを触っているのでそれ関連でEffectの管理を考えてみました。

Effect.js

cc.ComponentとしてEffectのマネージャーを作成する

export let Effect = cc.Class({
    extends: cc.Component,

    properties: {
        _effects: [],
        _isPause: false
    },
    statics: {
        main: null
    },

    // LIFE-CYCLE CALLBACKS:

    onEnable() {
        if (Effect.main)
            return;
        Effect.main = this;
    },
    onDisable() {

        if (Effect.main !== this)
            return;

        Effect.main = null;

    },
    update(dt) {
        if (this._isPause)
            return;
        //パフォーマンス不安
        this._effects = this._effects.filter((elm) => {
            if (elm._effect === null) {
                return false;
            }
            elm._timer += dt;
            let isDestory = !elm._effect.update(elm._timer);
            if (isDestory) {
                elm._effect.onDestroy();
            }
            return !isDestory;
        });
    },
    add(effect) {
        if (effect instanceof IEffect)
            this._effects.push({ _timer: 0, _effect: effect });
        else
            throw "effect type is must extends `IEffect`";
    },

    clear() {
        this._effects = [];
    },
    pause() {
        this._isPause = true;
    },
    resume() {
        this._isPause = false;
    }
});

add関数に渡すのはIEffectを継承して実装したエフェクトのインスタンスとする

export class IEffect {
    constructor(node = null) {
        this.node = node;
    }
    update(timeSec) {
        return timeSec <= 1.0;
    }
    onDestroy() {
        if (this.node !== null)
            this.node.destroy();
    }
}

Effectのupdate(dt)が追加したエフェクト全てのupdate(timeSec)に各経過時間を渡して呼んでいる
コンストラクタでnodeを登録しておけば自動でdestroy()をよんでもらえる。
cc.Nodeやcc.Componentを渡すことができる

Sample1

Sample1.js

import { Effect, IEffect } from "Effect";

class Sample1 extends IEffect {
    update(timeSec) {
        this.node.scale += 0.01;
        return timeSec <= 1;
    }
}
cc.Class({
    extends: cc.Component,

    start() {
        this.t = 0;
        Effect.main.add(new Sample1 (this.node));
    },
    update(dt) {
    },
});

Effectコンポーネントがアタッチされたノードをもつシーンで このスクリプトがアタッチされたプレハブを生成したりすればよい