JohnWick
JohnWick

Reputation: 5149

Phaser set group sprites' anchor property

I am new to Phaser and have a quick question. I have a group object called cups, and I am adding 6 sprites to it. However, if each sprite does not have it's anchor property set to 0.5,0.5, then they will not be placed where I intend them too. I can change each sprites anchor after adding it to the group, but I feel there must be a better way, such as

var myGroup = game.add.group();
..add sprites here
myGroup.anchor.setTo(0.5,0.5);

Here is my current code.

window.onload = function() {

    var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create, update: update });

    function preload() {
        game.load.image('table', 'assets/img/table.png');
        game.load.image('cup', 'assets/img/cup.png');
        game.load.image('ball', 'assets/img/ball.png');
    }

    function create() {
        var table = game.add.sprite(game.world.centerX, game.world.centerY, 'table');
        table.anchor.setTo(0.5,0.5);

        var cupW = game.cache.getImage('cup').width;
        var cupH = game.cache.getImage('cup').height;
        var cups = game.add.group();

        var cup = cups.create(game.world.centerX, cupH / 2, 'cup');
        cup.anchor.setTo(0.5,0.5);
        cup = cups.create(game.world.centerX - cupW, cupH / 2, 'cup');
        cup.anchor.setTo(0.5,0.5);
        cup = cups.create(game.world.centerX + cupW, cupH / 2, 'cup');
        cup.anchor.setTo(0.5,0.5);
        cup = cups.create(game.world.centerX - cupW / 2, cupH + (cupH / 2), 'cup');
        cup.anchor.setTo(0.5,0.5);
        cup = cups.create(game.world.centerX + cupW / 2 , cupH + (cupH / 2), 'cup');
        cup.anchor.setTo(0.5,0.5);
        cup = cups.create(game.world.centerX, (cupH * 2) + (cupH / 2), 'cup');
        cup.anchor.setTo(0.5,0.5);

        var ball = game.add.sprite(game.world.centerX, game.world.centerY,'ball');
        ball.anchor.setTo(0.5,0.5);

    }

    function update() {

    }

}

Upvotes: 2

Views: 5636

Answers (2)

jdnichollsc
jdnichollsc

Reputation: 1569

Following your code example, it's easier this way =>

cups.setAll('anchor.x', 0.5);
cups.setAll('anchor.y', 0.5);

Upvotes: 9

shovelshed
shovelshed

Reputation: 82

When you add items to a group they become children, and you can find them a reference to them in group.children, so you could do the following:

// Create your group and add all your sprites here first

var cups = game.add.group();
cups.create(x, y, 'cup1');
cups.create(x, y, 'cup2');
cups.create(x, y, 'cup3');
cups.create(x, y, 'cup4'); // and so on

// Then select the children of the group, and loop over them.

cups.children.forEach(function(cup){
    // Here you can apply the same properties to every cup.
    cup.anchor.setTo(0.5,0.5);
});

If you want to see a list of all the children, open up your javascript console and run this line:

console.log(cups.children);

Upvotes: 0

Related Questions