Game Development Reference
In-Depth Information
Handling mouse events and starting the crosshairs
The player in Flak Cannon will control
crosshairs
on the screen that they will use to target shots.
The crosshairs will be controlled by the mouse; the mouse button will be used to fire a
Flak
shell
at incoming
Enemy
planes.
The first thing we must do to support the
crosshairs
is to define a variable to hold the bitmap in
the properties definition section of the
Game
class. Note, we already created this in the properties,
this line of code is just for clarification.
private var crosshairs:Bitmap;
Now, in
newLevel()
, we will test to see if the crosshairs exists. If not, we will hide the mouse
pointer using the
Mouse.hide()
function and then define a new instance of the crosshairs
Bitmap
that we can add to the screen. Notice that if you are using Flex, the call to create a new instance
is slightly different than in Flash. This is because Flex already considers the
CrosshairsGif()
class to be a
Bitmap
, while in Flash, we need to create a new Bitmap instance by passing an
instance of
CrosshairsGif()
. The difference is subtle, but both sets of code are necessary to
support either technology.
if (crosshairs == null) {
Mouse.hide();
//***** Flex *****
//crosshairs = new CrosshairsGif();
//***** Flash *****
crosshairs = new Bitmap(new CrosshairsGif(0,0));
Now, we need to position the crosshairs on the screen. This is the first place where we use
gameWidth
and
gameHeight
that we passed in from
Main
. We will then add crosshairs to the screen
using
addChild()
. Finally, we will add a new event handler to the stage to listen for the
MouseEvent.MOUSE_MOVE
event, so we can move the crosshairs when the mouse is moved,
making it appear to move with the mouse.
crosshairs.x=gameWidth/2;
crosshairs.y=gameHeight/2;
addChild(crosshairs);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMoveListener, false, 0, true);
}
Now that we have our crosshairs on the screen, we need to do one more thing to support user
input. We need to listen for the mouse button click, so we know when to fire a flak shell for the
player. We do this by listening for the
MouseEvent.MOUSE_DOWN
event. This event is better for a
game like Flak Cannon than
MouseEvent.MOUSE_CLICK
, as that event will wait for the mouse button
to be pressed and released, while
MouseEvent.MOUSE_DOWN
will fire when the mouse is pressed
down. This will make the firing more responsive for the player.
stage.addEventListener(MouseEvent.MOUSE_DOWN, shootListener, false, 0, true);
Having now defined listeners for mouse event, we must also create functions for those listeners
to call. The first function
mouseMoveListener()
is quite simple. It is called whenever the mouse
moves to update the position of crosshairs.