Ch010 - Game Mechanic: Jumping on Enemies

Ch010 - Game Mechanic: Jumping on Enemies

Game Mechanic: Jumping on Enemies

The game mechanic of jumping on enemies to get rid of them has been made very popular by Mario games. It is a great way to use the jumping dynamic in a creative way. We can use the same technique as many Mario games use to do this. An enemy will kill our player unless our player is falling when they make contact.

What we need to know and what we will do

Our mechanic relies on us being able to check if we are jumping on our enemy. We will do this by checking to see if our player is on the way up or coming down from a jump.

To be able to do this step it would help if you knew about the following from this book;

Going over the code:

The code for a minimal example of the Jumping on Enemies game mechanic is shown here - https://jamm-labs.github.io/ggcp/game-mechanic-jump-on-enemies/game.js

In playState.preload add a line which creates a new type of enemy.

    game.load.image("newenemy", "https://cdn.glitch.com/05027ea3-2f71-hazard.png");

In playState.create add the following code either towards the end the function

  var enemy1 = game.add.sprite(370, 320, "newenemy");
  enemy1.type = "spider";

Have a look at the updated hitHazard function for the code that checks to see if the player is coming down from a jump by seeing if the y axis velocity is less than 0 and if the enemy type is ;

var hitHazard = function (player, hazard) {
    if (hazard.type === "enemy" && player.body.velocity.y > 0){
//  if (player.body.velocity.y > 0){
      hazard.kill();
    }
    else {
      player.kill();
      restart();
    }
};

In the code above the if statement makes checks to see if the enemy is of a type of spider. This is because you may have other possible different hazard types might be in the group. Some might be more static hazard types like a cactus. You can use this approach if you want to use a different types of enemy to your game. If that is not the case then you can use the more simple line which is commented out in the code example above.

That’s it. We hope you enjoy adding this game dynamic to your game to jump on enemies.