grinmonk

Centering an object relatively to its parent

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!

Share this post


Link to post
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

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

  • Recently Browsing   0 members

    No registered users viewing this page.