Jump to content
This forum will be closing down. Please move to the respective dedicated project forums.

Centering an object relatively to its parent


grinmonk
 Share

Recommended Posts

Hi! With this code I try to put a text object in the center of a sprite, which is in its turn is centered relatively to the world.

var sprite = game.add.sprite(0, 0, 'phaser');
    
sprite.anchor.set(0.5);
sprite.x = game.world.width * 0.5;
sprite.y = game.world.height * 0.5;
    
var text = game.make.text(sprite.width * 0.5, sprite.height * 0.5, "Yo", {
            font: "10px Arial",
            fill: "#ffffff",
            align: "center"
        });
text.anchor.set(0.5);
sprite.addChild(text);

But what I get is this:

centering.png

instead of this:

centering_right.png

What am I doing wrong and how to achive my goal? Thanks!

Link to comment
Share on other sites

var sprite = game.add.sprite(0, 0, 'sprite');
    
sprite.anchor.set(0.5);
sprite.x = game.world.width * 0.5;
sprite.y = game.world.height * 0.5;
    
var text = game.make.text(0, 0, "Yo", {
            font: "$10px Arial",
            fill: "#ffffff",
            align: "center"
        });
text.position.x -= text.width * 0.5;
text.position.y -= text.height * 0.5;
sprite.addChild(text);

You need to set the text position to 0, 0 :)

after text is created i add:

text.position.x -= text.width * 0.5;
text.position.y -= text.height * 0.5;

for the position based on the size of the text

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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