Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

2D XNA game mouse clicking

Tags:

c#

xna

I have a 2D game in which I use only the mouse as input. How can I make it so that my when the mouse hovers over a Texture2D object, the Texture2D and the mouse cursor change, and when the texture is clicked it moves to another place.

Simply put, I want to know how to do something when I hover over or click on a Texture2D.

like image 743
Ahmed Hegazy Avatar asked Mar 15 '12 01:03

Ahmed Hegazy


1 Answers

In XNA you can use the Mouse class to query user input.

The easiest way of doing it is to check the mouse state for each frame and react accordingly. Is the mouse position inside a certain area? Display a different cursor. Is the right button pressed during this frame? Show a menu. etc.

var mouseState = Mouse.GetState();

Get the mouse position in screen coordinates (relative to the top left corner):

var mousePosition = new Point(mouseState.X, mouseState.Y);

Change a texture when the mouse is inside a certain area:

Rectangle area = someRectangle;

// Check if the mouse position is inside the rectangle
if (area.Contains(mousePosition))
{
    backgroundTexture = hoverTexture;
}
else
{
    backgroundTexture = defaultTexture;
}

Do something while the left mouse button is clicked:

if (mouseState.LeftButton == ButtonState.Pressed)
{
    // Do cool stuff here
}

Remember though that you will always have information of the current frame. So while something cool may happen during the time the button is clicked, it will stop as soon as released.

To check for a single click you would have to store the mouse state of the last frame and compare what has changed:

// The active state from the last frame is now old
lastMouseState = currentMouseState;

// Get the mouse state relevant for this frame
currentMouseState = Mouse.GetState();

// Recognize a single click of the left mouse button
if (lastMouseState.LeftButton == ButtonState.Released && currentMouseState.LeftButton == ButtonState.Pressed)
{
    // React to the click
    // ...
    clickOccurred = true;
}

You could make it even more advanced and work with events. So you would still use the snippets from above, but instead of directly including the code for the action you would fire events: MouseIn, MouseOver, MouseOut. ButtonPush, ButtonPressed, ButtonRelease, etc.

like image 125
Lucius Avatar answered Sep 20 '22 08:09

Lucius