Game Development Reference
In-Depth Information
for that. But before we can use the class, we have to place an additional using -
instruction in the beginning of our program that tells the compiler that we will be
needing some classes that provide methods for handling input :
using Microsoft.Xna.Framework.Input;
The Mouse class has a method called GetState . This method gives us the current
mouse state. Using this current mouse state, we can find out where on the screen the
mouse is, whether the player is clicking on one of the buttons, and so on. The type
of the current mouse state is MouseState , and we can create a variable of that type to
store the current mouse state that the GetState method gives us:
MouseState currentMouseState = Mouse.GetState();
Now that we have this variable, we can retrieve the x and y -position of the mouse in
the screen using the properties X and Y of the variable of type MouseState . Just like
in the FlyingSprites program, we store this position in the variable balloonPosition :
balloonPosition = new Vector2(currentMouseState.X, currentMouseState.Y);
So, in every call of the Update method, we retrieve the current mouse position, and
we store this position in the variable balloonPosition . We then draw the balloon sprite
at that position in the Draw method. The final effect of this is that the balloon is
always drawn at the mouse position. If you press F5 and execute the program, you
will see exactly this behavior.
5.2.2 Methods and Properties
A method call can be either an expression or an instruction. spriteBatch.Begin(); is an
instruction, for example, but Mouse.GetState() is an expression, since the method has
a result (the mouse state). Retrieving a property is always an expression (which, in
turn, can be part of an instruction). We can extend the instruction syntax diagram
with method calls and assignments to properties:
And similarly, we can extend the expression syntax diagram with the following
part, which shows calling methods and properties as expressions, as well as creating
an object such as Vector2 with the new keyword:
Search WWH ::




Custom Search