Thomas Brooks
Thomas Brooks

Reputation: 49

How to do mouse selection on grid? Monogame/XNA

I am creating a game that uses tile based combat on a portion of the screen. I have already mapped a 2d array of nodes (each with a corner position to draw my units) and I have already done some tests with drawing the actual units. Now I need to start working on mouse selection, but am having trouble finding a way to map a mouse click to a particular node in the array. I have the positions stored in each node, but I don't know how exactly to use them. I would like to be able to have someone left click a square and have a way to register which square I actually selected. Any help?

This is an example of part of my grid which is in the bottom half of my screen

Upvotes: 0

Views: 677

Answers (1)

libertylocked
libertylocked

Reputation: 912

Rectangle has a method Contains(Point), and you can use it to easily detect if a point is inside the rectangle.


Assume your Node class has a property BoundingRectangle.

class Node
{
    // ...
    public Rectangle BoundingRectangle
    {
        get { return new Rectangle(x, y, width, height); }
    }
    // ...
}

Now to handle mouse clicks:

MouseState mouseState = Mouse.GetState();

if (mouseState.LeftButton == ButtonState.Pressed)
{
    foreach (Node n : nodes)
    {
        if (n.BoundingRectangle.Contains(mouseState.Position))
        {
            // TODO: Code to handle node being clicked...
        }
    }
}

Upvotes: 1

Related Questions