0

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

1
  • Show where your cell positions are stored? Apr 10, 2016 at 2:57

1 Answer 1

1

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...
        }
    }
}
1
  • This was exactly what I was looking for. Thanks, I'll look into this. Apr 10, 2016 at 4:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.