I have the following method, called in my update loop, to check if one of two buttons has been pressed.
private void CheckInputs()
{
if (CheckButton(startNewGameButtonTexture, startNewGameButtonPosition))
{
//break 1 is here
}
if (CheckButton(continueCareerButtonTexture, continueCareerButtonPosition))
{
//break 2 is here
}
}
Buttons are just rectangles, and if the mouse is over them, and the click is released the CheckButton bool returns true:
public bool CheckButton(Texture2D texture, Vector2 vector)
{
MouseState CurrentMouseState = Mouse.GetState();
bool outcome;
if (CurrentMouseState.X > vector.X && CurrentMouseState.X < vector.X + texture.Width &&
CurrentMouseState.Y > vector.Y && CurrentMouseState.Y < vector.Y + texture.Height)
{
if (CurrentMouseState.LeftButton == ButtonState.Released && PreviousMouseState == ButtonState.Pressed)
{
outcome = true;
}
else
{
outcome = false;
}
}
else
{
outcome = false;
}
PreviousMouseState = CurrentMouseState.LeftButton;
return outcome;
}
In the current order, the startNewGameButton works (ie debugging stops at break 1), but the continueCareerButton doesn't work (clicking on the button does not trigger break 2).
But if I change the order of the the checks to this:
private void CheckInputs()
{
if (CheckButton(continueCareerButtonTexture, continueCareerButtonPosition))
{
//break 2 is here
}
if (CheckButton(startNewGameButtonTexture, startNewGameButtonPosition))
{
//break 1 is here
}
}
the continueCareerButton now works (break 2), but the startNewGameButton now doesn't (break 1).
I think the mouse states must not be working properly, but I can't work out why.
You are setting your PreviousMouseState every time you check.
You should be setting it once per frame, the simplest way to do this is inside the Update()
function:
void Update(..) {
CurrentMouseState := Mouse.GetState()
// code...
PreviousMouseState = CurrentMouseState
}
Otherwise it will only ever work for the first call of your CheckButton()
function instead of every call.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments