In some Flash games author often has a need to display energy bar for
hero character or enemy character or both. In this tutorial you will
learn how to create reusable energy bar which you can ..., well reuse, in
all your future projects. Code is pure ActionScript 3.0. I'm trying to
develop this habit to write small chunks of useful code for my future
games :)
package
{
import flash.display.Sprite;
import flash.geom.Rectangle;
import flash.events.Event;
And now code explanation. First we need to import some classes like
Sprite, Rectangle and Event. Then we write our class. We are extending
Sprite class so we can draw that energy bar. We have two private
variables: _do which is Display Object, in this case Sprite of our hero
character and _ev which holds energy value. With this kind of class you
can pass whatever Sprite you want and attach energy bar to it.
Insert your hero. My hero is simple blue circle shape with big H letter
inside. Very creative. Anyway, set linkage properties as image below
shows, name this class 'hero' and use next code to create hero class.
package
{
import flash.display.MovieClip;
import flash.events.Event;
Place .as file in same folder where your .fla file is saved. You haven't
saved it yet? That's bad practise - do it now!
Previous code is just for testing purposes and you can also get away
without it.
Final step in this tutorial (yes, we are almost over) is to make game.as
class to put things together and make everything works right. Here is
your code:
package
{
import flash.display.Sprite;
import energyBar;
import flash.events.Event;
import flash.events.MouseEvent;
a.addEventListener(MouseEvent.CLICK, onClick);
}
When you make your own game you will probably not use energyBar in this
way, but instead energy value will decrease if your hero character gets
shot or is eaten by invinsible cosmic monster from Betelgeuse star system
or whatever.
Thanks for your time; I hope you have found this tutorial useful. And
fun.
*_*
Flanture