How to refactor and improve this XNA mouse input code?
- by Andrew Price
Currently I have something like this:
public bool IsLeftMouseButtonDown()
{
return currentMouseState.LeftButton == ButtonState.Pressed && previousMouseSate.LeftButton == ButtonState.Pressed;
}
public bool IsLeftMouseButtonPressed()
{
return currentMouseState.LeftButton == ButtonState.Pressed && previousMouseSate.LeftButton == ButtonState.Released;
}
public bool IsLeftMouseButtonUp()
{
return currentMouseState.LeftButton == ButtonState.Released && previousMouseSate.LeftButton == ButtonState.Released;
}
public bool IsLeftMouseButtonReleased()
{
return currentMouseState.LeftButton == ButtonState.Released && previousMouseSate.LeftButton == ButtonState.Pressed;
}
This is fine. In fact, I kind of like it. However, I'd hate to have to repeat this same code five times (for right, middle, X1, X2). Is there any way to pass in the button I want to the function so I could have something like this?
public bool IsMouseButtonDown(MouseButton button)
{
return currentMouseState.IsPressed(button) && previousMouseState.IsPressed(button);
}
public bool IsMouseButtonPressed(MouseButton button)
{
return currentMouseState.IsPressed(button) && !previousMouseState.IsPressed(button);
}
public bool IsMouseButtonUp(MouseButton button)
{
return !currentMouseState.IsPressed(button) && previousMouseState.IsPressed(button);
}
public bool IsMouseButtonReleased(MouseButton button)
{
return !currentMouseState.IsPressed(button) && previousMouseState.IsPressed(button);
}
I suppose I could create some custom enumeration and switch through it in each function, but I'd like to first see if there is a built-in solution or a better way..
Thanks!