简体   繁体   中英

C# Monogame - detect mouse hold

I'm writing a complex GUI for my game's main menu. I have already created a ButtonGUI class with it's own constructor with the parameters of button text, text color etc. I have a background texture drawn behind the text for every button, to make it look pretty. So I implemented a simple mouse input system:

void DetectBtnInput(ButtonGUI btn)
{
    if (mouseRect.Intersects(btn.SourceRect))
    {
        btn.IsHovered = true;
        if (mouseState.LeftButton == ButtonState.Pressed) settingsWindow.isOpen = true;
    }
}

This method is called in Update(GameTime gameTime) for each instance of the ButtonGUI class. So mouseRect = new Rectangle(mouseState.X, mouseState.Y, 1, 1); each instance of the ButtonGUI class has a Rectangle SourceRect property, which is equal to the position of the button passed to the constructor (obviously the button's size is the same every time). The logic behind the above code is simple, if the mouse is hovering the button instance's SourceRect , btn.IsHovered is set to true, it changes text color. When clicked, my WindowGUI class instance opens with additional settings.

So my aim is at making these buttons look nice and have the Windows styled button mechanics. So I am looking for a code to check for mouse hold-like event and have for example a bool that changes the button texture or whatever I can do myself. But the problem is that I tried incorporating the solution people give about the previousMouseState and the newMouseState , but I am not certain as if it works in Monogame as it worked in XNA... Or was my implementation wrong? Can I have a clearer example on how you handle mouse-hold in your games? Thanks in advance!

If you mean the player can click and hold (as per question title), and nothing happens until they then release. previous and current state should work fine as an implementation such as.

Forgive any incorrections in syntax, hopefully you can take this as pseudo code enough to make your own.

MouseState prev, curr;
curr = GetMouseState();

update()
{
  prev = curr;
  curr = GetMouseState();

  // Simple check for a mouse click (from being held down)
  if (curr == MouseState.Up && prev == MouseState.Down)
  {
    // Do mouse stuff here
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM