Question

I'm trying to add an event handler to a button press of a XNA gamepad using Microsoft Visual c#. I've tried putting a test for the button state to be pressed in the update method but since the update method is called like 60 times a second, it checks for the button press and is registered a bunch of times. IS THERE A WAY TO MAKE AN EVENT LISTENER FOR THE BUTTON TO BE PRESSED AND CALL THE EVENT ONCE INSTEAD OF A BUNCH OF TIMES? Here's my code in the update method that doesn't work:

    protected override void Update(GameTime gameTime)
    {
          if(GamePad.GetState(PlayerIndex.One).Buttons.Y == ButtonState.Pressed)
    {
              //do some code
          }
    }

this doesn't do what i need, can someone please point me in the right direction?

Was it helpful?

Solution

Usually the logic for single press is this:

if (button_is_pressed_now && button_was_not_pressed_last_frame)
{ /* there was a single press */ }

Which translates to your case so:

if(currentGamepadState(PlayerIndex.One).Buttons.Y == ButtonState.Pressed &&
  previousGamepadState(PlayerIndex.One).Buttons.Y != ButtonState.Pressed)
{
          //do some code
}

This means you need to keep track of previous gamepad state. Microsoft's official tutorial has more on that: http://xbox.create.msdn.com/en-US/education/tutorial/2dgame/getting_started

That said, you don't really need an event handler for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top