Positioning sprites

Now that you know how to create and display sprites, let’s find out how to position and resize them.

In the earlier example the cat sprite was added to the stage at the top left corner. The cat has an x position of 0 and a y position of 0. You can change the position of the cat by changing the values of its x and y properties. Here’s how you can center the cat in the stage by setting its x and y property values to 96.

  1. cat.x = 96;
  2. cat.y = 96;

Add these two lines of code anywhere inside the setup function, after you’ve created the sprite.

  1. function setup() {
  2. //Create the `cat` sprite
  3. let cat = new Sprite(resources["images/cat.png"].texture);
  4. //Change the sprite's position
  5. cat.x = 96;
  6. cat.y = 96;
  7. //Add the cat to the stage so you can see it
  8. app.stage.addChild(cat);
  9. }

(Note: In this example, Sprite is an alias for PIXI.Sprite, TextureCache is an alias for PIXI.utils.TextureCache, and resources is an alias for PIXI.loader.resources as described earlier. I’ll be using aliases that follow this same format for all Pixi objects and methods in the example code from now on.)

These two new lines of code will move the cat 96 pixels to the right, and 96 pixels down. Here’s the result:

Cat centered on the stage

The cat’s top left corner (its left ear) represents its x and y anchor point. To make the cat move to the right, increase the value of its x property. To make the cat move down, increase the value of its y property. If the cat has an x value of 0, it will be at the very left side of the stage. If it has a y value of 0, it will be at the very top of the stage.

Cat centered on the stage - diagram

Instead of setting the sprite’s x and y properties independently, you can set them together in a single line of code, like this:

  1. sprite.position.set(x, y)