Game Development Reference
In-Depth Information
public function mouseMoveListener(e:MouseEvent):void {
crosshairs.x = e.stageX-(crosshairs.width/2);
crosshairs.y = e.stageY-(crosshairs.height/2);
}
There are a couple of interesting things to note about this function. The first is self-explanatory
but should still be noted. We can find the position of the mouse relative to the stage using the
stageX
and
stageY
properties of the
MouseEvent
object. The second thing is more subtle. We
need to subtract half of the width and height from
stageX
and
stageY
to position the
crosshairs
properly (see Figure 5-1).
Figure 5-1. Adjusting the crosshairs into the center
We need to do this because of the way bitmaps are loaded dynamically in AS3. Without any
adjustments, a bitmap image will load at its upper-left-hand registration point (see top of Figure 4-12).
If we stopped there, shots fired would not explode in the center of the crosshairs, but in the upper-left.
By performing the adjustment (see bottom of Figure 4-12), you can see that the center of the
crosshairs is now where the mouse pointer would be and is also the point at which shots will explode.
Next, we need to write a function that will fire shots when the player presses the mouse button.
That function is
shootListener()
:
public function shootListener(e:MouseEvent):void {
The first thing we to do in this function is to check and see if the player has any shots left to fire
from the cannon. This is quite easy to accomplish by simply creating an
if:then
statement to
check the value of the shots variable:
if (shots > 0) {
If shots are remaining, we drop into the
if:then
statement and create an instance of the
Shot
class,
add it to the stage, push it into
shotArray()
, and then decrement the
shot
variable. Notice that we
subtract
(crosshairs.width/2)
from
mouseX
and
(crosshairs.height/2)
from
mouseY
. We do this to
center the shot in the middle of the crosshairs when it explodes into a Flak explosion.
tempShot = new Shot(gameWidth/2,gameHeight,mouseX-
(crosshairs.width/2),mouseY-(crosshairs.height/2));
this.addChild(tempShot);
shotArray.push(tempShot);
shots--;