How to refactor and improve this XNA mouse input code?
Posted
by
Andrew Price
on Game Development
See other posts from Game Development
or by Andrew Price
Published on 2012-02-20T04:24:04Z
Indexed on
2012/06/11
4:47 UTC
Read the original article
Hit count: 332
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!
© Game Development or respective owner