How can I make my background game responsive?

I want to change my game size and my background change too (responsive), so what can I do? I found some tutorials, but it seems outdated.

// Main.ts:
/** @type {import("../typings/phaser.d.ts")} */

import { LoadScene } from './scenes/LoadScene';
import { MenuScene } from './scenes/MenuScene';

const config = {
  scale: {
    mode: Phaser.Scale.FIT,
    autoCenter: Phaser.Scale.CENTER_BOTH,
    width: 1080,
    height: 720,
  },
  scene: [
    LoadScene, MenuScene
  ]
};

var game = new Phaser.Game(config);

export default config;
// MenuScene:

import { CST } from '../CST';
import config from '../main';

export class MenuScene extends Phaser.Scene {
  constructor() {
    super({
      key: CST.SCENES.MENU
    })
  }

  init() {
  }

  preload() {
  }

  create() {
    let playButton = this.add.image(this.game.renderer.width / 2, this.game.renderer.height * 0.60, CST.IMAGE.PLAY).setDepth(1);

    this.add.image(this.game.renderer.width / 2, this.game.renderer.height * 0.20, CST.IMAGE.LOGO).setDepth(1);
    this.add.image(0, 0, CST.IMAGE.TITLE).setOrigin(0);

    playButton.on("pointerover", () => {
    })
  }
}

:wave:

It depends on what you want. FIT scales the whole canvas to fit its container and is easy to use. For a truly responsive game you would use RESIZE but then it’s up to you to reposition and rescale game objects in a resize event handler.

1 Like

If you need the background to act like background-size:cover in CSS, you can simulate that by changing the size of your background base on the game’s size. This is how I make it in my project

// add background to scene
const background = scene.add.image(0, 0, 'texture');

// resize background to cover the screen
// since my game is full screen, I use the window size as my game size
function resize(){
    const newSize = backgroundCover(background, {width: window.innerWidth, height: window.innerHeight});
    background.setDisplaySize(newSize.width, newSize.height);
}
resize();

// on game resize
scene.scale.on('resize', resize);

You can find the backgroundCover() function at https://github.com/studiometa/background-cover

1 Like

You can also cover your background this way

background.setPosition(window.innerWidth/2, window.innerHeight/2);
scaleX = (window.innerWidth / background.width);
scaleY = (window.innerHeight / background.height);
scale = Math.max(scaleX, scaleY);
background.setScale(scale);