Question:
How do you draw your health as an image in Game Maker?


Answer:

First, in the Create Event of your character's object, make a variable to represent health. You can use drag-and-drop or use code. I'll use code. Make a variable like the one below. (The number doesn't really matter for now. It can be updated and tweaked as you work on your game.)

health=3;

You can go ahead and make a sprite to represent your health. It can be anything you want and whatever size you want. For this example, I'm making a circle that is 32x32 pixels to represent my health.

Now, make a new object. Name it whatever you want. Ours will be called objHealthDisplay. In this object, add a Draw Event. This time we want the action for this event to be execute a piece of code. In the code box, we put this code:

if (objMyCharacter.health==3)
    {
    draw_sprite(sprHealth,0,32,32);
    draw_sprite(sprHealth,0,64,32);
    draw_sprite(sprHealth,0,96,32);
    }
else if (objMyCharacter.health==2)
    {
    draw_sprite(sprHealth,0,32,32);
    draw_sprite(sprHealth,0,64,32);
    }
else if (objMyCharacter.health==1)
    {
    draw_sprite(sprHealth,0,32,32);
    }

Let's break it down!
  • objMyCharacter is object name of my main character. objMyCharacter has a variable called health (we made it in the above step) When I do objMyCharacter.health, it gets the value of the health variable. So in the draw of the object objHealthDisplay, we want to ask what is the health of the main character.
  • Based on the health of the main character, we want to draw our health sprite. (sprHealth in this case)
  • If we have 3 health, draw 3 health sprites. If we have 2 health, draw two, and so on and so forth.
Now that we have those objects, put them both in a room. If all went well, you should see the health sprites at the top of your screen! Now, when you want your health to go down, just change the health variable of the main character and the images will reflect that change! Simple, right?

Now this code is just one of the ways to do this. That's the great thing about coding in general: once you get the basics, you can try other ways to do the same thing. As you learn, you will find your own unique way to code things!

Page updated: March 23rd, 2015 @ 6:21 AM Eastern Time

Copyright 2010-2023 ExecuteCode.com.
All Rights Reserved.
Our other websites: