After reading the xNa practical keyboard article-moving an image based on the arrow key (3), do you still feel a bit confused? Let's see how xNa handles mouse events, save the previous experiments. Let's create a new project named "mysecondgame". This time we will not give allCodeI have read the previousArticleIt is clear.
Define the "global variables" in the class ":
/// <Summary>
/// Image Position
/// </Summary>
Private vector2 picposition;
/// <Summary>
/// Define a 2D Texture Image
/// </Summary>
Private texture2d texture;
Let's instantiate a 2-dimensional vector variable in the constructor:
Picposition = new vector2 ();
It is used in update (gametime). I have said before that this function is a very important function.
Instantiate the following in the loadcontent () function that loads the game content:
Texture = texture2d. fromfile (graphics. graphicsdevice, "test.jpg"); // you can copy the previous image to the current debug file.
Start Update (gametime) to capture mouse events.
Mousestate = mouse. getstate (); // gets the mouse click status
If (mousestate. leftbutton = buttonstate. Pressed) // obtain whether the left mouse button is pressed
{
// Locate the image to the current clicked position
Picposition. x = mousestate. X;
Picposition. Y = mousestate. Y;
}
Just a few lines of code have completed positioning the image with the mouse. MS is such a silly programming.
Go to the draw (gametime) function and draw images loaded to 2D Texture objects to the game interface.
Spritebatch. Begin ();
Spritebatch. Draw (texture, picposition, color. White );
Spritebatch. End ();
OK. Click F5 to run it. Click the left mouse button on the game interface. Is the picture on the game interface moved to the place where the mouse is clicked...
However, this effect is not very beautiful, and we can't see the process of moving images. Review the previous article, we mentioned using the keyboard to control image movement. So, it is not difficult to move the mouse and click the image slowly.
The code will be published in the next article.