AS3 Health Bar Tutorial (Mini-Lesson)

I’ve received a request to teach how to make a health bar in actionscript 3. Health bars can be found in all sorts of games, so I decided not to confine it to a single tutorial series. Instead, I’ve made this the first of a new section of Mini-Lessons on this site, to cover miscellaneous small game mechanics which can be used in a variety of games.

This tutorial is heavily image-based :-)

Here’s the demo of what we are going to create in this tutorial.

Easy to make. Easy to customize.

Pretty cool, huh?

Setting up the stage

First, we need to set up the project with a visual representation of the health bar.Using the Rectangle tool, draw a long horizontal rectangle. Set its width to 100 pixels and its height 10 pixels, with the properties seen below.

It should look something like this (only smaller):

Select everything and convert it into a Movie Clip symbol (using F8 or the Modify menu), setting its name to Health Bar.

Give it an instance name of healthBar so that we can access it in our program.


Double-click on the object to edit it, and select only the colored bar part of it – not the outline. Convert this part into another Movie Clip, called Bar Color, and make sure to set its registration to the left. This way, we can stretch the bar around the left edge when the health changes.

Give it an instance name of barColor.

Heads up! If you’re following along and you just converted the color of the bar into a symbol, you’ll have noticed that this brought the barColor to the front of the stage, blocking part of the outline from view. To fix this we will create 3 layers inside the healthBar object. (To insert a new layer, navigate to Insert –> Timeline –> Layer)

Now, you want to cut and “paste-in-place” the barColor object into the middle layer, which is the barColor Layer.

Cut and paste-in-place the outline of the rectangle into the top layer, which you can just call the foreground Layer.

And finally, draw and fill in a dark rectangle on the bottom layer, the background Layer. (If you don’t want to draw a new rectangle, you can copy and paste-in-place the red rectangle of the color bar into this layer, and just set its color to dark gray.)

The 3 layers will look something like this (except each one should be in the same y-location)

Line them all up and you get a basic health bar!

The healthBar object is all set up! Go back to the main stage (“Scene 1”) , and make sure all you have on frame 1 of the timeline is your healthBar instance. Now that the object is built, feel free to use the Transform tool or panel to adjust the size of the bar. Make it nice and big to test it out (mine is at about 500% size), or keep it small and tuck it away in the corner of your game’s HUD. No matter how you scale the instance of the object, it won’t effect the functionality of our code — so go wild!

Also feel free to customize the colors, the height, the outline, the background… add or remove as much as you want to create a unique health bar which will fit the needs of your game.

Writing the Program

How will our program work? Simple. We figure out what percentage of HP the player has left. Then we set the scaleX of the barColor object to be equal to this percentage.

Start by defining a few variables. The maxHP is total amount of health your player has — I chose 100, just because it’s an easy number to work with, but any amount is OK. The currentHP is how much health the player actually has at any given time. We want to start the game with full health, so we’ll set it to the value of the maxHP. The final variable we need to define is the percentHP, which is the currentHP divided by the maxHP, and is a number between 0 and 1.

Click on frame 1 of the timeline, and open up the actions panel (Window –> Actions). Declare these variables at the top of your program.


var maxHP:int = 100;
var currentHP:int = maxHP;
var percentHP:Number = currentHP / maxHP;

Next, create a function which you can use to update the health bar. It’s super simple.

function updateHealthBar():void
{
     percentHP = currentHP / maxHP;
     healthBar.barColor.scaleX = percentHP;
}

Whenever you call this function, it will do two things. First it will set the percentHP to the current ratio of how much HP your player has left. Then it will take the barColor object which we created inside the healthBar, and set its scaleX property to the percentHP. This creates a shrinking effect the smaller the currentHP becomes.

That’s all the code it takes to make the health bar work.

Testing it out

If you compile and run your game (Control –> Test Movie), there is absolutely no indication that any of our code is working. That’s because we’ve only created the function to update the bar. Here’s how to test it out and see that it’s working.

Quick Test

If you want to do a quick test to check that everything is working as we intended, all you need to do is set the currentHP to a different initial value than the maxHP. For example, if in line 2 of your program when you declare the variable, if you set the currentHP to 50 and test your game, the bar now is only half the width. Bingo!

Better Test

Let’s try out this health bar in action, to create what is shown in the demo of this tutorial.

Draw a new rectangle onto the stage, beneath the health bar. This will be our “attack button”. Make it look snazzy if you want, or just keep it as a bland rectangle. This is what mine looks like:

Now convert this to a symbol, taking care to choose the Button category instead of a standard Movie Clip. I named my symbol “Attack Button”, and gave it the instance name of attackButton.

Now that you have an object to click on and interact with, go back to your actionscript.

Underneath the updateHP function, add an event listener for clicking on the attack button:

attackButton.addEventListener(MouseEvent.CLICK, attackButtonClicked);

This will call the attackButtonClicked function every time the player clicks on the attackButton.

What do we need to accomplish in the attackButtonClicked function? For starters, we need to decrease the currentHP. Then we want to call the updateHealthBar function, but only after we check to make sure the player hasn’t died yet, in which case we call any extra code to end the game, and we set his currentHP to 0 (to make sure the health bar doesn’t go into the negative side).

Here is the rest of the code of the entire program:

function attackButtonClicked(e:MouseEvent):void
{
     currentHP -= 10;
     if(currentHP <= 0) //if the player died
     {
          currentHP = 0; //set his HP to zero, (just in case)
          trace("You died! :P"); //add any extra death-code here
     }
     updateHealthBar(); //update the healthBar
}

We are done.

Run your game, and you’ll get the following:

Want the source? Here ya go: download source code for free :-)

Thanks for listening, now go make something awesome with this!

Ben

PS. If you’ve got any great ideas for more mini-lessons, let me know what you’d like to learn and I can make it happen.

34 comments on “AS3 Health Bar Tutorial (Mini-Lesson)

  1. Michael says:

    Awesome first mini tutorial!! How about an idea for a mini tutorial might be like how to save and load a game? I don’t know how long of a tutorial that would be but its something that would be cool to know. As always, thanks for the tutorials and cheap it up. Your helping us noobs greatly!

  2. RenZ says:

    Wow!!! Awesome :D Thanks A lot I really need this one :D

  3. Adam Thomas says:

    Right Ben quick comment required if you can to answer this will be greatly appreciated:
    How do I program a health to reset when I restart my game?
    I’m doing it in AS3

    • Ben Reynolds says:

      Whenever you restart your game, add the following code:

      currentHP = maxHP;
      updateHealthBar();

      That should be all you need. Let me know if any problems come up.

  4. Adam Thomas says:

    Ok Ben I’ve put the code in and I’ve got two bars, one for fuel and one for the health. I want it so that when I restart the game with either the fuel has ran out resulting in game over and I’ve taken damage to both reset when I restart the game, if you want me to type the code here I will.

  5. Adam Thomas says:

    Ok I tested it and I found the bars weren’t resetting at the same time when I restart, how do I fix this?
    Your assistance is greatly appreciated

    • Ben Reynolds says:

      OK, here’s what I would do.

      If you don’t already have one, create a function called restartGame(), which will be the only function you need to call whenever you want to restart the game.

      function restartGame():void{
      currentHP = maxHP;
      updateHealthBar();

      currentFuel = maxFuel;
      updateFuelBar();
      }

      updateFuelBar() should contain the same code as updateHealthBar() does, just with your fuel-related variables instead of the health-related ones.

      I’m fairly sure this will fix your problem.

  6. John says:

    I’m obviously doing something wrong…. I keep getting “1046: Type was not found or was not a compile-time constant: healthBar.”

    • Ben Reynolds says:

      Did you set the instance name of the health bar object on the stage to “healthBar”, by using the Properties panel? Let me know if that doesn’t fix it.

  7. John.T says:

    How would I use this if i’m working in .as file.
    this is the code I tried using for when my enemy hits the the barricade I made(the goal is to keep the barricade up so I gave it a health bar).

    var maxHP:int = 100;
    var currentHP:int = maxHP;
    var percentHP:Number = currentHP / maxHP;
    var healthBar:MChealthBar = new MChealthBar();

    healthBar.x = 435.10;
    healthBar.y = 10.90;

    addChild(healthBar);

    function updateHealthBar():void
    {
    percentHP = currentHP / maxHP;
    healthBar.barColor.scaleX = percentHP;
    }

    function onTick( e:TimerEvent ):void
    {
    if ( Math.random() < 0.025 )
    {
    var randomX:Number = Math.random() * 400;
    var newEnemy:MCenemy = new MCenemy();
    newEnemy.y = -15;
    newEnemy.x = randomX;
    army.push( newEnemy );
    addChild( newEnemy );
    }
    for each ( var enemy:MCenemy in army )
    {
    if(enemy.y < barricade.y)
    {
    enemy.y += .75;
    }
    if ( bullet.hitTestObject(enemy))
    {
    enemy.parent.removeChild(enemy);
    }
    if (enemy.y == gameStop)
    {
    gameTimer.stop();
    enemyTimer.stop();
    stage.removeEventListener(KeyboardEvent.KEY_DOWN, keyDownHandeler)
    if (enemy.hitTestObject(barricade))
    {
    currentHP -= 10;
    }

  8. […] make a functional health bar. if anyone is looking to create one, I highly suggest this tutorial:  https://as3gametuts.com/2012/02/10/actionscript-health-bar-tutorial/   « Progress Update   No Comments    […]

  9. Sanoj says:

    Thanks a lot Ben! I’m planning to use this in my application too! :) \m/

  10. Ed says:

    Hey there, i tried putting the following in my class and it did not work..

    I first declared this:

    private var hpBar:BarHealth; //Added the linkage already

    Then i initialized:

    hpBar = new BarHealth();
    addChild(hpBar);
    hpBar.x = 50;
    hpBar.y = 520;
    maxHP = 100;
    currentHP = maxHP;
    percentHP = currentHP/maxHP;

    Added this into my startGame function:

    stage.addEventListener(Event.ENTER_FRAME,updateHealthBar);

    Added function:

    function updateHealthBar(evt:Event)
    {
    percentHP = currentHP / maxHP;
    hpBar.barColor.scaleX = percentHP;
    }

    Attached the function to my update function:

    if(mobArray[i].hitTestPoint(wizard.x, wizard.y))
    {
    currentHP -= 10;
    updateHealthBar();
    }

    It gave me this error “Incorrect number of Arguments: Expected 1”

    Help would be appreciated, thanks :)

    • Ben Reynolds says:

      Your problem is that you are calling the “updateHealthBar” function from the ENTER_FRAME event listener, as well as from the code beneath. When it’s called from ENTER_FRAME it has 1 argument passed into it — that’s why you included the “evt:Event”. But when you called updateHealthBar() from the hit-test code beneath, you don’t include any arguments, so it gets an error: “Incorrect number of Arguments: Expected 1”

      I have 2 suggested solutions.

      My first is to remove the “stage.addEventListener(Event.ENTER_FRAME,updateHealthBar);” line altogether, because I can’t see what good it’s doing right now. Then you could just get rid of the “eve:Event” in the updateHealthBar function, and it will run fine.

      But if for some reason I can’t see, you do need the health bar to be constantly updated every frame, as well as when the hit-test occurs, then you wouldn’t want to delete the event listener. Instead, you can replace the header of the updateHealthBar function with this:

      function updateHealthBar(evt:Event = null) {

      … this way, even if don’t provide an argument, actionscript will set its default value to “null” (nothing). This lets you call the same function from the event listener and from the other code.

  11. mark says:

    how about a loading screen tutorial? :)

  12. raymond says:

    hi ben i done in a .AS file for coding
    package {

    import flash.display.MovieClip;

    public class HealthBar extends MovieClip {

    public function HealthBar() {

    var maxHP:int = 100;
    var currentHP:int = maxHP;
    var percentHP:Number = currentHP / maxHP;

    function updateHealthBar():void
    {
    percentHP = currentHP / maxHP;
    healthBar.barColor.scaleX = percentHP;
    }

    attackButton.addEventListener(MouseEvent.CLICK, attackButtonClicked);

    function attackButtonClicked(e:MouseEvent):void
    {
    currentHP -= 10;
    if(currentHP <= 0) //if the player died
    {
    currentHP = 0; //set his HP to zero, (just in case)
    trace("You died! :P"); //add any extra death-code here
    }
    updateHealthBar(); //update the healthBar
    }
    }
    }

    }

    i got the error 1046: Type was not found or was not a complie-time constart: MouseEvent.

    • Ben Reynolds says:

      You need to import the MouseEvent code into your file to make it work.

      Just under where you wrote: import flash.display.MovieClip;
      add:
      import flash.events.MouseEvent;

      It should work. Hope this helps! :-)

  13. Haukur says:

    Where it say’s “add any extra death-code here” I added gotoAndStop(4); because I want to have a “Game Over” screen at frame 4. It works but I get an error msg: “TypeError: Error #1009: Cannot access a property or method of a null object reference. at >filename_fla<::MainTimeLine/loop()" Can anybody help?

  14. Bex says:

    Hi wen i do the quick test even when using your one it doesn’t seem to work??

    • blob says:

      That is right, for the quick test you must make sure that only the action of the function updateHealthBar is uncommitted like this:
      //function updateHealthBar():void
      //{
      percentHP = currentHP / maxHP;
      healthBar.healthBarColor.scaleX = percentHP;
      //}

  15. marvel shaan says:

    hii, i want to automatically decrease health bar,if player collide with enemy………so how to assign attack button to enemy??..thx…

  16. sariyam476 says:

    hii any help…,,i want to decrease player health,if he collide with enemy…so,how to assign attack button to enemy???..thx

  17. Mike says:

    Can you please help me I want to replace the trace(“You died :P”);
    With a command that will direct it will go another scene :) Can you please help me please?

  18. brein says:

    where will i put the functions

  19. Venti says:

    Like Bex, I’m pretty sure I did exactly what u did and the quick test isn’t working =/

  20. Lino Junior says:

    hello! I really liked her initiative in your site. I’m starting to program flash games and I have a difficulty in the game I’m creating now. Gostria to know if you can help me with my doubts.

  21. aspiee says:

    how to add it as child on stage via as3 code and how to minus the live when enemy hit it.

Leave a reply to Ben Reynolds Cancel reply