Phaser设置了sprites的锚属性

时间:2015-01-29 02:19:02

标签: javascript html5 phaser-framework

我是Phaser的新手并且有一个简单的问题。我有一个名为杯子的组对象,我正在添加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() {

    }

}

2 个答案:

答案 0 :(得分:8)

这样更容易=>

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

答案 1 :(得分:1)

当您向群组添加项目时,他们会成为子项目,您可以在 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);
相关问题