Jump to content

How do I align text with a sprite ?


bluedot
 Share

Recommended Posts

Hi,

 

I'm just starting out HTML5 and JS game development using Phaser. I've managed to find most of the info I'm looking for but I can't find the answer to the above question.

I'm looking for a method to display an animated sprite that also has a text label overlay that will always be centred to the sprite. How can I do this ?

 

Thanks.

 

Link to comment
Share on other sites

Set an anchor on the sprite and then when you create the text you need to set the X/Y of the text to the same as the player.

in the loop you could just put:

spriteText.x = player.x;

spriteText.y = player.y;

that would have it constantly on the sprite but you can offset the text by adding a little more to the values to position to your liking.

Link to comment
Share on other sites

Alternatively if you do the following, the text will become 'part of' the sprite (it will become one of its children) and be positioned relative to it:

sprite.addChild(spriteText); // add the text to the sprite as a child, just like a group spriteText.x = spriteText.width * -0.5; // center the textspriteText.y = -10 // position the text 10 pixels above the origin of the sprite
Link to comment
Share on other sites

Hi lewster32,

 

Using your calculations put the text in the wrong position. It ended up like this:

 

player1_text.jpg

 

So I changed the code to something like:

this.tilesList[0] = this.game.add.sprite(this.tilesX, this.tilesY, 'playerbar');this.player1Text = this.game.add.text(0, 0, 'Player 1', { font: "30px Arial", fill: "#ffffff", align: "left" });this.tilesList[0].addChild(this.player1Text);this.player1Text.x =  (this.tilesList[0].width - this.player1Text.width) / 2;this.player1Text.y = (this.tilesList[0].height - this.player1Text.height) / 2;

Which gave the correct result:

 

player1_text_f.jpg

 

Same method of working out centred  text as all other text widgets. :-)

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...