# How to place a sprite in the center of the world in Phaser

I am very new to Phaser. Here is what I did:

  <!DOCTYPE html>
<html>
<body>
<script src="phaser.js"></script>
<script>
var game = new Phaser.Game(500, 500, Phaser.AUTO, '', {
create : create,
update : update
});

}

function create() {
game.stage.backgroundColor = "#1BDCFF";
dog = game.add.sprite(game.world.centerX, game.world.centerY, 'dog');
}

function update() {

}

</script>
</body>


Shouldn't the dog appear in the center of the "world"? Here is how it looks like :

I then tried something like this :

var dogImage = game.cache.getImage('dog');
dog = game.add.sprite(game.world.centerX-dogImage.width/2, game.world.centerY-  dogImage.height/2, 'dog');


And now that I edited in this way the create function it does place the dog in the center. Is this the way of doing it or there's a more elegant way ?

Valkea has the right idea, but I recommend you modify the anchor of your Sprite to what you intend - in this case, the center of the sprite. If you were using P2 or Ninja physics, this is done automatically for you, but with Arcade physics, this defaults to the top-left corner. Simply call <your sprite>.anchor.setTo(0.5); to set both the x and y anchors to the middle.

Doing this will save you from having to account for the top left corner everywhere. The anchor point is used when transforming (flips, rotations, scales), measuring distances, when specifying a different collision box size than your sprite, and many more.

Have a look at the Phaser anchor example for a visual representation of the anchor and how it affects sprite positioning.

Update: the anchor property now belongs to Sprite.

The top left corner of your dog asset is most probably placed at the center of your game area.

In order to solve your problem, you should move the dog asset by half its height and width so it is centered on the given coordinates.

Maybe something like this :

var TmpImg = game.cache.getImage('dog');
game.add.sprite(game.world.centerX - TmpImg.width/2.0,game.world.centerY - TmpImg.height/2.0,'dog');


(I don't know Phaser, so I might be wrong)

• Thanks for the tip ! I edited the question . But I am not very sure if this is the right way to solve it so I hope that someone that knows Phaser will comment upon. – user3009269 Aug 3 '14 at 18:50
• well we added the same code portion at the same time ;) – Valkea Aug 3 '14 at 18:51
• ;) Nice! Couldn't do it again even if we wanted to ! – user3009269 Aug 3 '14 at 18:53

You could try to set the anchor of the dog to 0.5, like this:

dog.anchor.setTo(0.5);