How do I scale sprites in Phaser 3?
Often times when making a game, I will add a sprite to the stage to find out it looks bigger in the game than it did in the editing program. Often times this produces comical results. Think of a coin being twice as big as the player! If it is really much too big then I will re-edit the image and scale it down. Sometimes though scaling makes sense. I use scaling in all my game to make things fit nicely on the screen.
Using Maths for scale
Personally, I like to scale objects based on the game’s dimensions. For example, I might make the width of the player 10 percent of the game’s width and then scale it proportionally. This isn’t just for Phaser, this is maths. It will work in any game as long as you know the size of the stage or viewport in case of scrolling games and can set the height and width of objects. If you are able to set a scale it is even easier. Phaser has a lot of built-in things that make it easy for us.
Getting the size of the game
We can get the size of the game by accessing the config object in the game.
- var gameWidth=game.config.width;
- var gameHeight=game.config.height;
Setting a scale
There are several ways to set a scale on a sprite.
- sprite.setScale(.5);
sets the scale of the sprite to 50% of the original size - sprite.scaleX=.1;
sets the width of the sprite to 10% of the original - sprite.displayWidth=game.config.width*.1; sprite.scaleY=sprite.scaleX
sets the displayWidth to a percentage of the game’s width, and then scales the object proportionally
What is the difference between displayWidth and width?
A sprite has width, height, displayHeight and displayWidth properties. So what’s up with that and which do you use?
The width and height properties refer to the size of the sprite’s image as it was loaded into the game. The displayWidth and displayHeight are the width and height of the sprite itself. If you want to change the sprite’s dimensions use displayWidth, Thanks to browserGamesHubs.com for providing information on this subject.
Here is an example of make 10 randomly placed faces of different sizes
class SceneMain extends Phaser.Scene { constructor() { super('SceneMain'); } preload() { this.load.image("face", "images/face.png"); } create() { for (var i = 0; i < 10; i++) { //get the width and height of the //game from the config file var h = game.config.height; var w = game.config.width; //create some random coordinates var x = Phaser.Math.Between(0, w); var y = Phaser.Math.Between(0, h); //create a random width var width = Phaser.Math.Between(50, 200); //make a face sprite and place it //at the random place var face = this.add.sprite(x, y, "face"); //set the width of the sprite face.displayWidth = width; //scale evenly face.scaleY = face.scaleX; } } update() {} }