相位器设置组精灵的锚属性

Phaser set group sprites' anchor property

本文关键字:属性 精灵 设置      更新时间:2023-09-26

我是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() {
    }
}

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

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

当您将项目添加到组中时,它们将成为子项,并且可以在 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);