Home > OS >  How to make a image dynamically change to text
How to make a image dynamically change to text

Time:07-01

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()))

CodePudding user response:

A fast solution with the Phaser.GameObjects.Text, is to use displayWidth/displayHeight and Phaser.Display.Align.In.Center;.
Maybe this works also for your UseCase.

Here a 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/[email protected]/dist/phaser.js"></script>

  • Related