Jump to content

Phaser group forEachAlive loop in reverse


Azumi
 Share

Recommended Posts

Hello.

When I use forEachAlive loop on a group I see that it goes in ascending index order, I need to loop through group children in reverse order without changing their indexes or display order.

I searched on google, in documentation ad in examples but I can't find a solution.

I will be very grateful for any help.

Link to comment
Share on other sites

Thanks for all the help. I looked into source code of the framework and added changed versions of functions that already exists there. I changed the "for" loop in iterate function. It probably is a little bit of an overkill but it works fine so far.

 

Phaser.Group.prototype.reverseIterate = function (key, value, returnType, callback, callbackContext, args) {

    if (this.children.length === 0)
    {
        if (returnType === Phaser.Group.RETURN_TOTAL)
        {
            return 0;
        }
        else if (returnType === Phaser.Group.RETURN_ALL)
        {
            return [];
        }
    }

    var total = 0;

    if (returnType === Phaser.Group.RETURN_ALL)
    {
        var output = [];
    }

    for (var i = this.children.length - 1; i >= 0 ; i--)
    {
        if (this.children[i][key] === value)
        {
            total++;

            if (callback)
            {
                if (args)
                {
                    args[0] = this.children[i];
                    callback.apply(callbackContext, args);
                }
                else
                {
                    callback.call(callbackContext, this.children[i]);
                }
            }

            if (returnType === Phaser.Group.RETURN_CHILD)
            {
                return this.children[i];
            }
            else if (returnType === Phaser.Group.RETURN_ALL)
            {
                output.push(this.children[i]);
            }
        }
    }

    if (returnType === Phaser.Group.RETURN_TOTAL)
    {
        return total;
    }
    else if (returnType === Phaser.Group.RETURN_ALL)
    {
        return output;
    }
    else
    {
        //  RETURN_CHILD or RETURN_NONE
        return null;
    }

};

Phaser.Group.prototype.forEachAliveReverse = function (callback, callbackContext) {

    var args;

    if (arguments.length > 2)
    {
        args = [null];

        for (var i = 2; i < arguments.length; i++)
        {
            args.push(arguments[i]);
        }
    }

    this.reverseIterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);

};

 

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...