Game Development Reference
In-Depth Information
was pressed or not. Then, we override the
HandleInput
method to check if the player
has clicked the left mouse button. If the mouse position is within the boundaries of
the sprite at that time, we know that the player has pressed the button and we set
the value of the member variable to
true
. How can we check if the mouse position
is within the boundaries of the sprite? For that, we can use the
Rectangle
class. As a
first step, we construct a
Rectangle
object that encompasses the sprite, as follows:
Rectangle rect =
new
Rectangle((
int
)GlobalPosition.X, (
int
)GlobalPosition.Y,
sprite.Width, sprite.Height);
We pass four parameters to the
Rectangle
constructor. The first two indicate at which
position the rectangle is located. Note that we use the
global
position here, because
we want to check if the mouse pointer is within the sprite at its actual, global po-
sition. The second two parameters provide the width and height of the rectangle,
which is the same as the width and height of the sprite. Then, we can simply use
the
Contains
method to find out if the current mouse position is within the rectan-
gle boundaries. The
Contains
method returns a boolean value, which we store in the
member variable:
pressed = inputHelper.MouseLeftButtonPressed() &&
rect.Contains((
int
)inputHelper.MousePosition.X,
(
int
)inputHelper.MousePosition.Y);
Finally, we add a property
Pressed
to the
Button
class, that indicates if the button is
currently pressed or not. For the complete class, see Listing
17.1
.
Now that we have a button class, we can add a help button to the game world
(see the
JewelJamGameWorld
class):
helpButton =
new
Button("spr_button_help", 2, "help_button");
helpButton.Position =
new
Vector2(1268, 20);
this
.Add(helpButton);
Since we want to display a help frame when the player presses the help button, we
also add a help frame to the game world. We set its visibility flag to
false
so that it
is not yet visible:
helpFrame =
new
SpriteGameObject("spr_frame_help", 2, "help_frame");
helpFrame.Position =
new
Vector2(636, 120);
helpFrame.Visible =
false
;
this
.Add(helpFrame);
Now we have to make sure that when the player presses the help button, the help
frame visibility is toggled. We can do this using the following
if
-instruction in the
HandleInput
method of the
JewelJamGameWorld
class:
if
(helpButton.Pressed)
helpFrame.Visible = !helpFrame.Visible;