'Phaser 3 interactive hitarea of a container

I have a container containing an image and some text; We are facing an issue with the interactive hitarea of the container

this.image = this.add.image(0, 0, 'GreenButtonBox').setOrigin(0.5).setScale(2);
this.text = this.add.text(0, 0, "Click", { font: "bold 35px Arial", fill: '#ffffff' }).setOrigin(0.5).setScale(1);
this.container = this.add.container(400, 400, [this.image, this.text])
    .setSize(this.image.width, this.image.height)
    .setInteractive()
    .on('pointerup', this.SubmitAnswer);

In the case above the interactive part of the button is located in the middle (maybe due to the scale of the image?

I also tried adding new Phaser.Geom.Rectangle to the interactive function as such

.setInteractive(new Phaser.Geom.Rectangle(0, 0, this.image.width, this.image.height), Phaser.Geom.Rectangle.Contains)

but the clickable area become the lower right corner of the button; wheras with

.setInteractive(new Phaser.Geom.Rectangle((this.image.width / 2) * -1, (this.image.height / 2) * -1, this.image.width, this.image.height), Phaser.Geom.Rectangle.Contains)

the clickable area becomes the uper left part of the button;

Do I need to account for the scale myself? such as

.setInteractive(new Phaser.Geom.Rectangle((this.image.width / 2) * -1, (this.image.height / 2) * -1, this.image.width * 2, this.image.height * 2), Phaser.Geom.Rectangle.Contains)

This actually works

I'm confused as to why I need to scale the image again when I'm taking the image width and height for the container width and height.

Am I missing something?



Solution 1:[1]

You are right, height and width won't work (they hold the original size), but you could simply use the properties displayWidth and displayHeight, this properties gives you the right size (especially after scaling), calculation is handled by phaser.

Here a small demo illustrating this:

let Scene = {
      preload(){
        this.load.image('ship', 'https://labs.phaser.io/assets/sprites/ship.png');
      },
      create(){
      
      this.image = this.add.image(0, 0, 'ship').setOrigin(0.5)
          console.info(`before Scale width: ${this.image.width}, height: ${this.image.height}, displayWidth: ${this.image.displayWidth}, displayHeight:${this.image.displayHeight}` );
           this.image.setScale(2);
          console.info(`after Scale width: ${this.image.width}, height: ${this.image.height}, displayWidth: ${this.image.displayWidth}, displayHeight:${this.image.displayHeight}` );
      }
    }
    
    const config = {
      type: Phaser.AUTO,
      width:400,
      height:200,
      scene: Scene,
     banner: false
    }
   const game = new Phaser.Game(config)
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/phaser.js"></script>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1