Instead of having a fixed background, it would be cool to have a scrolling background that moved downwards (forever) to make it look like you are flying through space. Phaser provides an infinite “tiled” background for doing just this.

Task Definition

  • Find a tileable background image and add it to your project (one is provided at the bottom of this page if you want to use it).
  • Replace your existing background image using this.add.tileSprite(x, y, width, height, image-name); instead of this.add.image.
  • In your update() method, modify the tilePositionY property of your space background.

Hints

A tiling sprite is one that is essentially infinitely big as it will simply repeat over and over again in all directions. If you do this with a regular sprite, you will get ugly seams where the edge of the first copy of the texture matches up with the second copy of the texture. However, if you find a ‘tileable’ texture, then it will just look like you have a massive background that goes on forever.

Create a tileable background using this.add.tileSprite(x, y, width, height, image-name) where x and y are the x,y co-ordinates of the ‘first’ image, width and height describe how often the image should repeat itself and image-name is the image name, similar to when loading a sprite.

You can then ‘slide’ the background in a direction using object.tilePosition.y -= 1;.

Here are the steps you will need to take during this task;

  • Add the image to the assets folder of your project.
  • Preload the image in your preload() function just like with a regular image.
  • Add the tiling background to your game using this.tiledBackground = this.add.tileSprite(0, 0, 1200, 1600, ‘image-name’);
  • In your update() method you should modify the tilePositionY property on your background using this.tiledBackground.tilePositionY -= 1;.

Sample Tiling Background

Download the starfield image used in the example below;

Solution

Here is a sample solution to this problem…

Add the following lines of code in MainGameScene.js...

preload() {
	this.load.image('space-tiled', 'assets/images/starfield-tiling.jpg');
}

create() {
	this.tiledBackground = this.add.tileSprite(0, 0, 1200, 1600, 'space-tiled');
}

update() {
	this.tiledBackground.tilePositionY -= 1;
}