Scaling sprites

Just like the background, the original image for our spaceship may be either too big or too small. In my case, it is tiny, and I need to scale it a bit. Let's see how we can do that:

  1. To set custom scaling in the form of a float number, use the sprite.setScale(x, y) method:
      // Create ship
ship = this.add.sprite(100, 100, 'ship');
ship.setScale(4, 4);
  1. Along with the global variables, the create implementation of our game should look as follows:
      const game = new Phaser.Game(config);
let ship;

function create() {
// Create background
const image = this.add.image(
this.cameras.main.width / 2,
this.cameras.main.height / 2,
'background'
);
let scaleX = this.cameras.main.width / image.width;
let scaleY = this.cameras.main.height / image.height;
let scale = Math.max(scaleX, scaleY);
image.setScale(scale).setScrollFactor(0);

// Create ship
ship = this.add.sprite(100, 100, 'ship');
ship.setScale(4, 4);
}
  1. Now, restart the application. You should see a spaceship image displayed at the position 100:100 on the screen. It has also been scaled to be four times bigger than the original image:

Typically, you want your assets to be the size that the game requires them to be so that you don't waste CPU and RAM on scaling things at runtime. However, you should still know how to scale images; that is why we used a smaller ship and then resized it.

Now, let's look at how we can handle keyboard input to move the ship around the screen.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.250.169