LoginSignup
6
7

More than 5 years have passed since last update.

[tmlib.js]要素を複数作るときはgroupを作ると便利

Posted at

要素を複数作るときはgroupを作ると便利

敵とかエフェクトとかなんもかんもaddChildTo(this)してると、管理用のメンバが増えてややこしくなる。

tm.define("TestScene", {
    superClass: "tm.app.Scene",

    init: function() {
        this.superInit();

        this.enemys = []; // これがあんまり好きくない

        for (var i=0, len=10; i<len; ++i) {
            var enemy = tm.display.RectangleShape()
                .addChildTo(this);
            this.enemys.push(enemy);
        }

        // 全体になにかする
        this.enemys.each(function (l) {
            l.x += 100;
        });
    },
});

そこで、まとめる用グループを作っとけばいい感じになる。

tm.define("TestScene", {
    superClass: "tm.app.Scene",

    init: function() {
        this.superInit();
        this.fromJSON({
            children: {
                enemyGroup: "tm.display.CanvasElement",
            },
        });

        for (var i=0, len=10; i<len; ++i) {
            var enemy = tm.display.RectangleShape()
                .addChildTo(this.enemyGroup);
        }

        // 全体になにかする
        this.enemyGroup.children.each(function (l) {
            l.x += 100;
        });
    },
});

ついでに、for文かくのも面倒なので、こうするともっとすっきりする。

tm.define("TestScene", {
    superClass: "tm.app.Scene",

    init: function() {
        this.superInit();
        this.fromJSON({
            children: {
                enemyGroup: "tm.display.CanvasElement",
            },
        });

        (10).times(function () {
            var enemy = tm.display.RectangleShape()
                .addChildTo(this.enemyGroup);
        });

        // 全体になにかする
        this.enemyGroup.children.each(function (l) {
            l.x += 100;
        });
    },
});

というメモでした。

ちなみに、timesっていう便利関数はtmlib.jsのもので、標準じゃないのでご注意。

6
7
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
6
7