Phaser3: How to create a Graphic with text?

Viewed 518

I'm using Phaser3 on my Angular project and so far I managed to create a Graphic Square and a Text. However, it seems complicated and mundane to treat them as separate. Is there a way to create one object that allows me to integrate both a Graphic shape and text together?

This is what my current code is:

    this.graphics = this.add.graphics();
    this.graphics.lineStyle(1,0xff0000);
    this.graphics.fillStyle(0x02455f, .5);
    this.graphics.strokeRect(100,200,250,250);
    this.graphics.fillRect(100,200,250,250);
    this.helloWorld = this.add.text(
      225,
      300,
      "Hello World", {
        font: "40px Arial",
        color: "#ffffff"
      }
    );

The above code creates a square and a Text and I have positioned them to be near each other, this is how it looks: What the code has shown

I want to treat this as its own separate thing but I can't when it's coded the way it is, is there a better option to create a single object that lets me add both styles?

2 Answers

I suggest to use Phaser.GameObjects.Container

A Container Game Object.

A Container, as the name implies, can 'contain' other types of Game Object. When a Game Object is added to a Container, the Container becomes responsible for the rendering of it.

[...]

If you modify a transform property of the Container, such as Container.x or Container.rotation then it will automatically influence all children as well.

I'm abit late to the party, but a different way can be, to create a new texture and draw/write the text onto it. (based on the official example)

You "just" have to:

  1. create a graphics object
  2. create a text object
  3. create a renderTexture
  4. draw graphics and text onto the renderTexture
  5. delete the created objects
  6. now use the created new texture, when and as needed.

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

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

function create () {
    
    let graphics = this.make.graphics();
    graphics.lineStyle(1,0xff0000);
    graphics.fillStyle(0x02455f, .5);
    graphics.strokeRect(10, 20, 160, 80);
    graphics.fillRect(10, 20, 160, 80);
    
    let helloWorld = this.add.text( 35, 50, "Hello World")
      .setFont("20px Arial")
      .setColor('#ffffff');
    
    let renderTexture = this.add.renderTexture(9, 19, 172, 102);
    
    renderTexture.draw(graphics);
    renderTexture.draw(helloWorld);
    
    renderTexture.saveTexture('newTexture');
    
    graphics.destroy();
    helloWorld.destroy();
    renderTexture.destroy();
    
    let image = this.add.image(100,100, 'newTexture').setOrigin(.5);
    
     this.tweens.add({
        targets: image,
        angle: {from: 0, to: 360},
        duration: 6000,
        repeat:-1
    });
    
    
}

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

Related