Monday, October 28, 2013

Intro to GML Part 3: A Simple Hit Points System

Ok, now that I've shown you variables and the if statement, we can build something useful with them.  Once again, this stuff is specific to Game Maker, so it may or may not be helpful if you're using something else.

Here's some general things you would do to create a hit points system for one of your objects.  First, you'd need to set a maximum the object can have, then fill it up.

So, in the object's create event you'd want:

//In Create Event

maxHP = 100; //Could be any number, change it depending on your needs
HP = maxHP; //Fills up HP to the max

Woo!  Now your object has hit points that do nothing!

The system we're going to use is pretty simple and will only work with games that use collision as being hit.  You know, like Mario games.

How does that work?  Well, you'll need to put this in the player's collision with enemy event:

//In Collision with Enemy

HP -= other.damage; //Player's HP is reduced by the enemy's damage


As is, this system won't work all that great.  Why?  Since collision will be checked every step, the enemy will reduce your HP really quickly.  To fix this, you'll have to add a time after being hit that the player can't be damaged.  There are lots of ways to do this, but this solution will use a "hurt" variable and an alarm.

Add hurt=0 to the create event like this:

//In Create Event

maxHP = 100; //Could be any number, change it depending on your needs
HP = maxHP; //Fills up HP to the max
 
hurt = 0; // Player can only be hit when this variable is 0

We're just using "hurt" as a sort of switch.  If it's 1, the player can't be hit.

We'll need our friend the if statement in the collision event now.  Basically, "if the player has been hit, don't hit the player again."

//In Collision with Enemy
if (hurt != 0) exit; //Nothing after this gets done if the player has been hurt

HP -= other.damage; //Player's HP is reduced by the enemy's damage
hurt = 1;
alarm[0] = 90; //Amount of time you want the player to be "invincible" after a hit
In the alarm[0] event, we tell the player it can be hit again:

//Alarm[0]

hurt = 0;


That's all you need from the player's side.  You'll need an enemy object, and a damage variable in it to have a workable damage system.

No comments:

Post a Comment