Create an HTML5 game like “Drop Wizard” with Phaser – patrolling enemies

Welcome to the third part of the creation of Drop Wizard game. A small recap:

* Create an HTML5 game like “Drop Wizard” with Phaser – player movement showed you how to create a level with its platforms and make the player move around it.

* Create an HTML5 game like “Drop Wizard” with Phaser – player fire, by extending sprite class was focused on player capability of firing bullets, by extending Phaser’s Sprite class.

Now it’s time to add enemies to the game, and such enemies must be able to patrol the platform they are placed on. Enemies too will be created as an extension to Sprite class, so the only difficult thing will be making them move on their platform without falling down.

Have a look at the result:

You can change the direction your Wizard – actually your red square – is moving by clicking on the stage, but above all watch the enemies as they patrol their platforms.

How can we make enemies patrol the platforms using Arcade physics? Have a look at the source code, with highlighted lines to let you see what changed since previous step:

You should be already able to extend Sprite class to create new enemies, so I am only focusing on patrol routine.

Line 102: this function is automatically called at each update, for every Enemy instance in the game.

Line 103: if the current enemy collides with something in platformGroup group – which contains all platforms – then moveEnemy function is called.

Line 104: finally enemy velocity is updated according to xSpeed property. The key to make the enemy change direction can be found in this property. Let’s see how we can change it.

Line 107: this function is called when an enemy hits a platform, which should always happen when the enemy is already on the platform, but it’s useful to place the code here in case you want to create the enemy in an empty space, so it can land on a platform, then move.

Line 108: here is the key of the script: thanks to enemy and platform arguments passed at line 107, we can know which enemy and which platform we are talking about, and check if the enemy is getting close to platform edge, according to its position, its direction and platform position.

Line 109: in this case, we just invert enemy speed.

And this is how we added patrolling enemies in a few lines. Next time, we’ll complete the level by making both enemies and Wizard killable, meanwhile you can download the source code.