3

I'm new to C Sharp, and writing a game w/ the XNA Framework.

I'm trying to establish variables for the buttons on the XBox 360 controller, so I can reconfigure the buttons' game functions in one place and not have to change direct references to the buttons everywhere.

So if I want to assign a button to "attack", instead of this:

if (gamePadState.IsButtonDown(Buttons.B)
{
   // do game logic
}

I want to do this:

if (gamePadState.IsButtonDown(MyAttackButton)
{
   // do game logic
}

Any ideas? I'm sure it's a very simple solution, but I've tried several approaches and none have worked yet. Thanks!

Singleton
  • 3,701
  • 3
  • 24
  • 37
Scott
  • 81
  • 2

3 Answers3

5

Buttons is just an enum, so you just need to create a variable with that name like

Buttons MyAttackButton = Buttons.B;
Brian Rasmussen
  • 114,645
  • 34
  • 221
  • 317
2

An alternative would be to define an enum somewhere:

public enum MyButtons
{
    AttackButton = Buttons.B,
    DefendButton = Buttons.A
}

Then to test it:

if (gamePadState.IsButtonDown((Buttons)MyButtons.DefendButton))
1

You could also create a dictionary:

enum MyButtons { ShootButton, JumpButton }

Dictionary<MyButtons, Buttons> inputMap = new Dictionary<MyButtons, Buttons>()
{
    { MyButtons.ShootButton, Buttons.Y },
    { MyButtons.JumpButton,  Buttons.B },
}

...

if (gamePadState.IsButtonDown(inputMap[MyButtons.ShootButton]))
{
    // Shoot...
}

The advantage of this method is that the button map can be modified at runtime, so you can use it to implement customizable control settings.

Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
  • Be aware that using enums as dictionary keys will generate garbage unless a custom IComparer is used. On the PC this won't be an issue, but on the Xbox 360, with its less-than-stellar GC, you might run into problems. – Tom Lint Nov 18 '14 at 10:10