In this guide, we will be taking a look at how to manipulate the position of images and sprites in Phaser 3. Being able to change the x and y positions of objects in your game is very useful and will allow you to add some awesome mechanics. Before we begin, I will assume you already created a scene and added a sprite or image. Don’t have a scene added? I would recommend checking out this tutorial I wrote. If you have no images or sprites yet, and you need to learn how to add them, check out this guide.

If you haven’t assigned the return value of the add.sprite method yet, this will be necessary. For example, change this:

this.add.sprite(128, 128, "myimage");

To:

this.myImage = this.add.sprite(128, 128, "myimage");

At this point, we can change the position of our image or sprite. There are a few ways of accomplishing this. There are a few methods to set position. Alternatively, you can directly set the x and y positions of a sprite or image.

Setting Positions via Methods

One way to set the position of a sprite or image is using the setPosition method. Normally, it’s common to enter the new x and y position as arguments like so:

this.myImage.setPosition(128, 256);

You can also set the position of a sprite or image on specific axes.

To set the x position of a sprite or image via a method, you can write:

this.myImage.setX(320);

To add, if you want to set the y position of a sprite or image via methods, you can add:

this.myImage.setY(240);

Setting Positions Directly

You can also set the x and y positions of a sprite or image without methods by directly setting the properties. I probably wouldn’t recommend changing positions this way (though I occasionally do), but you can type:

this.myImage.x = 280;

Of course, since you’re setting properties, you can increment the values as well like so:

this.myImage.x += 32;

The same concept applies to setting the y position directly. For example, you could write:

this.myImage.y = 48;

To increment the y position, you can also simply write:

this.myImage.y += 32;

Hopefully this guide helped you out. You may want to consider taking a look at the other tutorials in this series, if you liked this tutorial. If you would like to receive news of our future tutorials and courses, you can subscribe to our newsletter here. If you found this guide valuable, sharing this guide on your favorite social media would be highly appreciated as well. Stay tuned for more parts in this series.