How to make a image dynamically change to text

Viewed 61

I am making an online game using Phaser and I need to make buttons with text on them for it that can change based on the text because the text can be different each time. I tried checking the API document but when I put in the get size function to try to get the bounds of the text my button disappears or the code will stop working with the error saying cannot read properties of undefined (reading getBounds) and it will swap between the two every time I reload the page.

         count = Phaser.Math.Between(1,4)
         for(let i = 50;i <= 750;i = i +200){
            bingus = this.add.text(i, 400, quiz[category][difficulty][quest][count])
            answs.push(bingus)
            gorp.push(count)
            count++
            }
            if(count > 4){
               count = 1
            }
         }

         this.butt1.setDisplaySize(Phaser.Geom.Rectangle.GetSize(answs[gorp[0]].getBounds()))
1 Answers

You could use the Phaser.GameObjects.Text and it's displayWidth and / or displayHeight properties, together with the global Phaser.Display.Align.In.Center function.
Maybe this works also for your UseCase.

Basically:

  1. set the text of the text Object with setText
  2. get the current displayWidth and displayHeight of the text Object
  3. update/adjust the size of the button Object, also with displayWidth and displayHeight properties
  4. Center the text Object inside of the button Object, with the Phaser.Display.Align.In.Center function

Here a small working Demo:

document.body.style = 'margin:0;';

var config = {
    type: Phaser.AUTO,
    width: 500,
    height: 180,
    scene: {
        create
    },
    banner: false
}; 

let text;
let button;
let texts = ['first Text', 'Next', 'Second Text', 'Last', 'multiline1.\nmultiline2..\nmultiline3...' ];
let padding = 20;

let currentTextIdx = 0;

function create () {
    this.add.text(10, 10, 'Text cycles every 1000ms.')
    button = this.add.rectangle(250, 90, 100, 40, 0xff0000 )
        .setOrigin(.5);
    text = this.add.text(250, 90, texts[currentTextIdx])
        .setOrigin(.5);
        
    this.time.addEvent({ delay: 1000, startAt:999, loop: true , callback: _ => {
      currentTextIdx++;
      
      if(currentTextIdx >= texts.length){
           currentTextIdx = 0;
      }
      
      let newText =  texts[currentTextIdx];
      text.setText(newText);
      button.displayWidth = padding * 2 + text.displayWidth;
      button.displayHeight = padding * 2 + text.displayHeight;
      
      Phaser.Display.Align.In.Center(text, button);

    }});
}

new Phaser.Game(config);
<script src="//cdn.jsdelivr.net/npm/phaser@3.55.2/dist/phaser.js"></script>

Related