ionic-frameworkphaser-framework

How to correctly center a GameObject in the canvas


I am currently fiddling with Phaser3 with Ionic Capacitor to make a mobile app.

I'm not sure if this is a bug on Phaser3 or on Ionic, but for some reason the readonly values in the Scene (inside the create() method) this.scale.width and this.scale.canvas.width are both 0 when first read. This makes images added by e.g. this.add.image(this.scale.width / 2, 400, 'key') be rendered on the left border (zero on the X axis) of the game. Calling console.log(this.scale.width) sometimes fixes it for the subsequent readings.

I've set up the Phaser game into the app following this tutorial.

Is there any way to fix this, so either value always returns the correct game size? Or is there any other way I can center GameObjects in the canvas reliably?

The GameConfig used to launch the game is as follows:

const config = {
  type: Phaser.AUTO,
  scale: {
    mode: Phaser.Scale.RESIZE,
    autoCenter: Phaser.Scale.CENTER_BOTH
  },
  parent: 'game',
  backgroundColor: '#e0e4f1',
  scene: GameScene
};

Solution

  • Depending on your usecase you could simple use the resize the event (link to the documentation). Just add the positioning into the resize callback.

    Short Demo:
    (ShowCasing this)

    class Example extends Phaser.Scene
    {
        preload () { }
    
        create () {
            this.pic1 = this.add.rectangle (0, 0, 100, 100, 0xffffff);
            this.scale.on('resize', this.resize, this);
        }
    
        resize (gameSize, baseSize, displaySize, resolution){
            this.pic1.setPosition(gameSize.width/2, gameSize.height/2);
            this.pic1.setOrigin(.5)
        }
    }
    
    const config = {
        type: Phaser.CANVAS,
        backgroundColor: '#2dab2d',
        scale: {
            mode: Phaser.Scale.RESIZE,
            autoCenter: Phaser.Scale.CENTER_BOTH
        },
        scene: [ Example ]
    };
    
    const game = new Phaser.Game(config);
        <script src="//cdn.jsdelivr.net/npm/phaser/dist/phaser.min.js"></script>