Scaling in Phaser 3

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.

  1. sprite.setScale(.5);
    sets the scale of the sprite to 50% of the original size
  2. sprite.scaleX=.1;
    sets the width of the sprite to 10% of the original
  3. 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

 

Leave a Reply