Power Bar Controlled by Mouse Actions
by Diego Park
In this lesson we are going to develop a variant of the last tutorial. The power bar will be controlled by mouse. When the left mouse button is pressed, the power bar increases; and when it is released, the power bar decreases its width.
Modifying the last code
We are going to leave the movie clips of the last tutorial, and modify its source code. The change is very simple.
First, right-click on the movie clip power bar and select Actions (Figure 1). Please insert the following code:
/* movie clip initialization */
onClipEvent(load)
{
this._xscale=0;
speed=10;
/* variable shown in the text field */
scale=0;
/* mouse button is pressed or not */
pressed=false;
}
onClipEvent(mouseDown)
{
/* mouse button is pressed */
pressed=true;
}
onClipEvent(mouseUp)
{
/* mouse button released */
pressed=false;
}
onClipEvent(enterFrame)
{
/* if the mouse button is pressed */
if (pressed)
{
if (this._xscale<100)
this._xscale+=speed;
}
else
{
/* reduce the width */
if (_xscale>0)
this._xscale-=speed;
}
/* up-to-date the value to be shown in the text field */
scale=this._xscale;
}
Figure 1. Please right-click on the movie clip
power bar and select Actions.
As you see, we have inserted a new variable, called
pressed, which is set to true when the left button of the mouse is pressed; otherwise, it is set to false.
To handle mouse events, we need to add two handlers, for
imouseDown and
mouseUp --when the mouse button is pressed and when it is released. They do what we have explained: they set the variable
pressed to true or false.
Once we know the value of pressed -true or false-, we can deduce if the mouse button is pressed or not. As in the last tutorial, we increase or decrease the width of the power bar depending on the value of the Boolean. If the mouse button is pressed
(pressed==true) we want to increase its
_xscale; otherwise, if the mouse button is not pressed but the width of the power bar is greater than zero, we want to restore its width to null.
As you can see, the maintenance and modification of the movie clip is almost trivial.
ConclusionInserting almost trivial modifications, we can now control the width of the power bar with the left mouse button. This utility could be particularly attractive to interactive sports games.
[Download File][Page 1]
Visit our forums to discuss / post your problems.