Phaser 设置组精灵的锚 属性

Phaser set group sprites' anchor property

我是 Phaser 的新手,有一个快速的问题。我有一个名为 cups 的组对象,我向其中添加了 6 个精灵。但是,如果每个精灵都没有将其锚 属性 设置为 0.5,0.5,那么它们也不会被放置在我想要放置的位置。我可以在将每个精灵添加到组后更改锚点,但我觉得必须有更好的方法,例如

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

这是我当前的代码。

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() {

    }

}

当您将项目添加到组中时,它们会成为子项,您可以在 group.children 中找到对它们的引用,因此您可以执行以下操作:

// 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);
});

如果您想查看所有子项的列表,请打开您的 javascript 控制台并 运行 这一行:

console.log(cups.children);

按照您的代码示例,这样更容易 =>

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