Jump to content

Creating a sprite in the middle of the screen


Magnifisite
 Share

Recommended Posts

Hello,

 

I have to add a sprite to the center of the screen, I tried the following code but it didn't work for some reason:

txt = this.game.add.text((game.camera.x + game.camera.width) / 2, (game.camera.y + game.camera.height) / 2, "Test", {font: "30px Arial", fill: "#ffffff", stroke: '#000000', strokeThickness: 3});

Does anyone know a way to do this?

 

Edit: the center of the world != the center of my world (http://puu.sh/7e2cG.jpg)

Link to comment
Share on other sites

To centralize a sprite try this:

sprite = this.game.add.text(game.world.centerX,game.world.centerX, 'sprite_tag');

But it seems you want to centralize the text in the screen.

 

You can do this:

txt = this.game.add.text(game.world.centerX,game.world.centerX, , "Test", {font: "30px Arial", fill: "#ffffff", stroke: '#000000', strokeThickness: 3});txt.wordWrap = true;txt.wordWrapWidth = (0.95 * this.game.world.width);

I hope it helps.

Link to comment
Share on other sites

txt = this.game.add.text(game.world.centerX,game.world.centerY, "Test", {font: "30px Arial", fill: "#ffffff", stroke: '#000000', strokeThickness: 3});

Might be worth noting you may need to modify the centerX with a minus to center it a bit better because the center of the screen and the text will be slightly right. Other than that the code above should work fine. Also, you may need:

Txt.fixedToCamer = false;

That will keep it center. Pretty important bit of code.

Hope this helps :)

Link to comment
Share on other sites

** My first code was also wrong but after the edit it works!

 

Oh wow the solution was so easy and every answer here was so close.

 

Correct code:

txt = this.game.add.text(game.camera.width / 2, game.camera.height / 2, "Test", {font: "30px Arial", fill: "#ffffff", stroke: '#000000', strokeThickness: 3});txt.anchor.setTo(0.5, 0.5);txt.fixedToCamera = true;

You do not need any code in the update function.

Link to comment
Share on other sites

  • 2 years later...

I think a more correct answer for what you want if I understood right is the following: 

Like this the text will be in the center of the screen moving along with the camera

txt = this.game.add.text(game.camera.x + (game.width/2), game.camera.y + (game.height/2), "Test", {font: "30px Arial", fill: "#ffffff", stroke: '#000000', strokeThickness: 3});txt.anchor.setTo(0.5, 0.5);txt.fixedToCamera = true;
Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

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