Repeating or Tiled Background in Phaser

Creating tiled or repeating background is pretty straight forward in Phaser by using tileSprite.

Let say we have an image or a texture such as  which we want to use to create a background by repeating it in entire game area. Check out the highlighted line in the example below which is all that is required to create a nice tiled background in Phaser.

var TheGame = {
};

TheGame.Params = {
	baseWidth: 200,
	baseHeight: 200
};

TheGame.Boot = function (game) { };

TheGame.Boot.prototype =  {
    init: function () {
        this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
		this.game.scale.pageAlignHorizontally = true;
        this.game.scale.pageAlignVertically = true;
    },
    preload: function () {
        this.load.image("background", "repeatxy.png");
        this.load.image("loading", "loadingback.png");
    },
    create: function () {
        this.state.start("Loading");
    }	
};

TheGame.Loading = function (game) {
};

TheGame.Loading.prototype = {
    init: function () {
    },
    preload: function () {
        var loadingBar = this.add.sprite(this.world.centerX, this.world.centerY, "loading");
        loadingBar.anchor.setTo(0.5);
        this.load.setPreloadSprite(loadingBar);
    },
    create: function () {
       this.state.start("TheGame");
    }
};


TheGame.MyGame = function (game) {
};

TheGame.MyGame.prototype = {
    preload: function () {
    },
    create: function () {
        var background = mygame.add.tileSprite(0, 0, this.game.width, this.game.height, "background");
    },
};

var mygame;
window.onload = function () {
	mygame = new Phaser.Game(TheGame.Params.baseWidth, TheGame.Params.baseHeight, Phaser.AUTO, "mygame");	
	mygame.state.add("Boot", TheGame.Boot);
	mygame.state.add("Loading", TheGame.Loading);
	mygame.state.add("TheGame", TheGame.MyGame);
	mygame.state.start("Boot");
}

The example below demonstrates the code.


Leave A Comment

Your email address will not be published.