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.

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).

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

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!

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.

[…] 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 […]

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.

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?

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;
//}