Phaser Tutorial: creating your own Phaser plugins

One of the most interesting things provided by Phaser is the capability of extending its features thanks to a smart Plugin system which allows you to code external libraries to be used in more project or shared around the web.

I am going to show you how to create a plugin which will allow you to fade your screen to a given color in a given amount of time, then call a given state.

The example is the same shown in the post Phaser Tutorial: understanding Phaser states but this time, apart from resetting the score to zero when you restart the game, you will notice “fade to black” transitions when you press “play” button both in game title screen and in game over screen.

It’s just a tween and there’s nothing difficult in doing it, anyway from this simple effect you will be able to see how does a plugin work.

In showing you the source code, I will highlight the difference between this project and the original post about states.

First things first, I am loading the plugin in index.html:

<!doctype html>
<html>
	<head>
    		<script src="phaser.min.js"></script>
    		<script src="src/boot.js"></script>
		<script src="src/preload.js"></script>
		<script src="src/gametitle.js"></script>
		<script src="src/thegame.js"></script>
		<script src="src/gameover.js"></script>
          <script src="src/plugin.js"></script>		
    		<style>
    			body{margin:0}
    		</style>
		<script>
			(function() {
				var game = new Phaser.Game(320, 480, Phaser.CANVAS, "game");
				game.state.add("Boot",boot);
				game.state.add("Preload",preload);
				game.state.add("GameTitle",gameTitle);
				game.state.add("TheGame",theGame);
				game.state.add("GameOver",gameOver);
				game.state.start("Boot");
			})();    
		</script>
    </head>
    <body>
    </body>
</html>

Once I boot the game, in boot.js, the plugin is loaded:

var boot = function(game){
	console.log("%cStarting my awesome game", "color:white; background:red");
};
  
boot.prototype = {
	preload: function(){
          this.game.load.image("loading","assets/loading.png"); 
	},
  	create: function(){
		this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
		this.scale.pageAlignHorizontally = true;
		this.scale.setScreenSize();
		this.game.state.start("Preload");
		this.game.plugin=this.game.plugins.add(Phaser.Plugin.FadePlugin);
	}
}

gametitle.js and gameover.js call plugin’s fadeAndPlay method passing the color to fade to, the duration in seconds and the game state to call once the fade is completed. This is gametitle.js:

var gameTitle = function(game){}

gameTitle.prototype = {
  	create: function(){
		var gameTitle = this.game.add.sprite(160,160,"gametitle");
		gameTitle.anchor.setTo(0.5,0.5);
		var playButton = this.game.add.button(160,320,"play",this.playTheGame,this);
		playButton.anchor.setTo(0.5,0.5); 
	},
	playTheGame: function(){
		this.game.plugin.fadeAndPlay("rgb(0,0,0)",0.5,"TheGame");		
	}
}

and this is gameover.js:

var gameOver = function(game){}

gameOver.prototype = {
	init: function(score){
		alert("You scored: "+score)
	},
  	create: function(){
  		var gameOverTitle = this.game.add.sprite(160,160,"gameover");
		gameOverTitle.anchor.setTo(0.5,0.5);
		var playButton = this.game.add.button(160,320,"play",this.playTheGame,this);
		playButton.anchor.setTo(0.5,0.5);
	},
	playTheGame: function(){
		this.game.plugin.fadeAndPlay("rgb(0,0,0)",0.5,"TheGame");
	}
}

Now it’s time to have a look at the core of the whole project, the plugin itself written in plugin.js:

Phaser.Plugin.FadePlugin = function (game, parent) {
	Phaser.Plugin.call(this, game, parent);
};

Phaser.Plugin.FadePlugin.prototype = Object.create(Phaser.Plugin.prototype);
Phaser.Plugin.FadePlugin.prototype.constructor = Phaser.Plugin.SamplePlugin;

Phaser.Plugin.FadePlugin.prototype.fadeAndPlay = function (style,time,nextState) {
	this.crossFadeBitmap = this.game.make.bitmapData(this.game.width, this.game.height);
	this.crossFadeBitmap.rect(0, 0, this.game.width, this.game.height, style);
	this.overlay = this.game.add.sprite(0,0, this.crossFadeBitmap);
	this.overlay.alpha = 0;
	var fadeTween = this.game.add.tween(this.overlay);
	fadeTween.to({alpha:1},time*1000);
	fadeTween.onComplete.add(function(){
		this.game.state.start(nextState);
	},this);
	fadeTween.start();
};

While lines 1-6 are required by plugin engine in order for the plugin to be registered, fadeAndPlay function – lines 8-19 – creates a bitmap image of the given color covering the full game screen, initially sets it transparent then tween to fully opaque to give the “fade to color” effect.

In the end, the given state is called. Organizing the fade effect this way, as a plugin, will allow you to use this effect everytime you want, in any project, saving a lot of coding time.

Download the source code of the full project.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers