Create an HTML5 game like “Drop Wizard” with Phaser – player fire, by extending sprite class

Read all posts about "" game

In blog post “Create an HTML5 game like “Drop Wizard” with Phaser – player movement” we saw how to recreate player movement in a game like Drop Wizard.

Now it’s time to make player fire each time the wizard touches a new platform, in the direction the wizard is facing on.

To learn something new, we will handle bullets by extending Phaser‘s sprite class. First things first, let’s have a look at the result:

You can click on the game to make the player change direction, while the wizard will continuosly move, fall down and fire. Bullets are removed once they fly off the screen.

This is the source code, with highlighted code to make you see what’s new from original prototype source code:

window.onload = function() {
	
	var game = new Phaser.Game(480,320,Phaser.CANVAS,"",{preload:onPreload, create:onCreate, update:onUpdate});                

	var playerSpeed = 150;
	var bulletXSpeed = 3;
	var player;
	var platformGroup;
	var onPlatform = false;
	var readyToFire = false;

	function onPreload() {
		game.load.image("platform180","platform180.png");
		game.load.image("platform120","platform120.png");
		game.load.image("player","player.png");
		game.load.image("ground","ground.png");
		game.load.image("bullet","bullet.png");
	}

	function onCreate() {
		platformgroup = game.add.group();
		game.physics.startSystem(Phaser.Physics.ARCADE);
		player = game.add.sprite(240, 0, "player");
		player.anchor.setTo(0.5);
		game.physics.enable(player, Phaser.Physics.ARCADE);
		game.physics.arcade.gravity.y = playerSpeed;
		addPlatform(240,60,"platform180");  
		addPlatform(340,140,"platform120");  
		addPlatform(140,140,"platform120");
		addPlatform(420,220,"platform120"); 
		addPlatform(60,220,"platform120");
		addPlatform(100,316,"ground");
		addPlatform(380,316,"ground");
		game.input.onDown.add(changeDir, this);	
	}
	
	function addPlatform(posX,posY,asset){
		platform = game.add.sprite(posX,posY,asset)
		platform.anchor.setTo(0.5);
		game.physics.enable(platform, Phaser.Physics.ARCADE);
		platform.body.allowGravity = false;
		platform.body.immovable = true;
		platformgroup.add(platform);	
	}
	
	function onUpdate() {
		player.body.velocity.y = Math.abs(playerSpeed);
		player.body.velocity.x = 0;
		onPlatform = false;
		game.physics.arcade.collide(player, platformgroup, movePlayer);
		if(!onPlatform){
			readyToFire = true;
		}
		if(player.y>320){
			player.y = 0
		}
		if(player.x<12){
			player.x=12;
			playerSpeed*=-1
		}
		if(player.x>468){
			player.x=468;
			playerSpeed*=-1
		}

	}
	
	function movePlayer(){     
		player.body.velocity.x = playerSpeed;
		onPlatform = true;
		if(readyToFire){
			var bullet = new Bullet(game, player.x, player.y, playerSpeed, bulletXSpeed);
			game.add.existing(bullet);
			readyToFire = false;
		}
	}
	
	function changeDir(){
		playerSpeed *= -1;
	}
	
	Bullet = function (game, x, y, direction, speed) {
		Phaser.Sprite.call(this, game, x, y, "bullet");
		game.physics.enable(this, Phaser.Physics.ARCADE);
		this.xSpeed = direction*speed;
	};
	
	Bullet.prototype = Object.create(Phaser.Sprite.prototype);
	Bullet.prototype.constructor = Bullet;
	
	Bullet.prototype.update = function() {
     	this.body.velocity.y = 0;
		this.body.velocity.x = this.xSpeed;
		if(this.x<0 || this.x>480){
			this.destroy();
		}
	};
	
}

Let’s explain new lines:

Line 6: defining bullets horizontal speed.

Line 9: onPlatform Boolean variable tells us if the wizard is on a platform.

Line 10: readyToFire Boolean variable tells us if the wizard is ready to fire, that is if the wizard will fire once he lands on a new platform.

Line 17: preloading bullet image.

Line 49: at each onUpdate call, onPlatform is set to false. It will be movePlayer function, called at line 50, to set it to true if the wizard is on a platform.

Lines 51-53 : if the player is not on a platform, it means the wizard is falling down a platform so he will be ready to fire once he lands on a platform. That’s why readyToFire is set to true.

Line 70: onPlatform is set to true. This code is executed only if the player is on a platform, called by movePlayer at line 50.

Line 71: if the wizard is ready to fire, that means he just landed on a platform…

Line 72: creation of a new Bullet class instance. As you are about to see, Bullet will extend sprite class. I could have just generated the bullet as a simple sprite, then managed all sprites by putting them in an array and updating them one by one, but extending sprite class to create a proper class for the bullets highly improves code quality and reusability. Bullet also wants some arguments, such as the game itself, wizard x and y position, wizard speed – to determine the direction the wizard is facing – and bullet horizontal speed.

Line 73: once the bullet has been created, it’s time to add it to the game

Line 74: since the wizard just fired, he’s not longer ready to fire.

Now, it’s time to see Bullet class and how such class extends sprite.

Line 82: Bullet function definition, with the arguments we saw at line 72.

Line 83: Bullet will create a Sprite instance.

Line 84: enabling arcade physics for the bullet, in the same way we did it with the wizard at line 25.

Line 85: setting a property called xSpeed with bullet speed.

Line 88: this is how we say Bullet will extend Phaser’s built in Sprite class.

Line 89: the constructor, that is the function which creates a new bullet instance, is set to Bullet function.

Line 91: just like any other Phaser class, Bullet has an update function which will be automatically called at each game update.

Line 92: setting y velocity to zero, as the bullet travels horizontally.

Line 93: setting x velocity to xSpeed property.

Line 94-96: destroying the bullet when it leaves the stage.

And that’s how you can easily add bullets to your game by extending sprite class. During next step, we will place enemies to put our wizard in trouble. Meanwhile, download the source code.

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

214 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
// 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