Align a group of Obejcts (text)

Hi there,

I’m trying to align a group of Objects (text) in the middle of the scene. Phaser.Actions.GridAlign() seems to be the “right tool” for that. And even though centering is kinda ok, it still confuses me, especially if I do set x and y to 0.

So take a look.

create() {
    this.drawMainMenu()
}

drawMainMenu(){
    this._menu = this.add.group({
        name: 'game_scene_menu',
        active: true,
    })

    const menuButtonsLabels = ['Play', 'Settings', '----Quit----']

    menuButtonsLabels.forEach((btnTitle) => {
        const menuBtn = new TextButton(this, 0, 0, btnTitle, buttonFontStyle)
        this.menu.add(menuBtn)
        this.add.existing(menuBtn) // is there a way to skip this ?
    })


    Phaser.Actions.GridAlign(this.menu.getChildren(), {
        width: 1, // max 1 in a "row"
        height: -1,
        cellWidth: 140,
        cellHeight: 70,
        position: Phaser.Display.Align.TOP_LEFT,
        x: 0, // actually to top-left
        y: 0  // actually to top-left
    });
}

But the menu is off-screen (see the screen #1)

Why is it so off-screen ?

I get much better results if I use this.cameras.main.midPoint I also added some fake menu-buttons to menuButtonsLabels just to see how it scales.

const sceneCenterPoint = this.cameras.main.midPoint
    Phaser.Actions.GridAlign(this._mainMenu.getChildren(), {
      width: 1,
      height: -1,
      cellWidth: menuItemWidth,
      cellHeight: fontSize + 6,
      position: Phaser.Display.Align.CENTER,
      x: sceneCenterPoint.x,
      y: sceneCenterPoint.y
    });

It is centered, but it’s kinda grows to the bottom.
Do I miss something?

:wave:

GridAlign() only aligns game objects within grid cells. You still have to position the grid yourself. { x, y } is the position of the first grid cell, so I think you need to decrease y (estimate) to move it up the right amount.

Ok I see. It was even mentioned in the Docs :man_facepalming:

Is there any way to “visually debug” (outline or so) the grid ?

i would recommend using rex UI plugin. it helps a lot when you try to arrange UI.

and it have draw bounds method that can help you debug it’s placement

Thanks, I already saw some nice rexUI demos.
But I am just starting my journey with phaser and although rexUI would be a great help, I want to understand the basics first. After all GridAlign() is not only for UI or anything like that. :sweat_smile:

I think the only foolproof way is to align a bunch of rectangles into the same grid:

1 Like

Wow, thanks. This will help me a lot