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.
cat.x = 96;
cat.y = 96;
Add these two lines of code anywhere inside the setup
function, after you’ve created the sprite.
function setup() {
//Create the `cat` sprite
let cat = new Sprite(resources["images/cat.png"].texture);
//Change the sprite's position
cat.x = 96;
cat.y = 96;
//Add the cat to the stage so you can see it
app.stage.addChild(cat);
}
(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:
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.
Instead of setting the sprite’s x
and y
properties independently, you can set them together in a single line of code, like this:
sprite.position.set(x, y)