GamePad Input

OpenTK provides a simple-to-use, stateless GamePad input API under OpenTK.Input.GamePad. The API is modeled after XNA GamePad, so users of the latter will be comfortable using the OpenTK version and vice versa.

A GamePad is defined as an input device with a specific, well-defined layout:

  • One directional pad
  • Two thumb sticks with four axes of movement (left x-y, right x-y).
  • Two analogue triggers
  • Four main buttons (A, B, X, Y)
  • Up to seven auxiliary buttons (start, back, guide, left shoulder, right shoulder, left stick, right stick)

A given input device can be missing some of these capabilities. You can use GamePad.GetCapabilities() to retrieve the capabilities of a specific device:

for (int i = 0; i < 4; i++)
{
    var caps = GamePad.GetCapabilities(i);
    if (caps.HasAButton)
        ; // do something
 
    // Print all capabilities for this GamePad
    Console.WriteLine(caps.ToString());
}

You can retrieve the current state of a device using GamePad.GetState():

for (int i = 0; i < 4; i++)
{
    var state = GamePad.GetState(i);
    if (state.Button.A == ButtonState.Pressed)
        ; // do something
 
    // Print the current state for this GamePad
    Console.WriteLine(state.ToString());
}

To detect changes in the state of a GamePad, store and compare the new state with the previous state:

GamePadState old_state;
GamePadState state = GamePad.GetState(0);
 
if (state != old_state)
{
    if (state.Button.A == ButtonState.Pressed && old_state.Button.A == ButtonState.Released)
        ; // Button A was just pressed
    else if (state.Button.A == ButtonState.Pressed && old_state.Button.A == ButtonState.Pressed)
       ; // Button A is held
    else if (state.Button.A == ButtonState.Released && old_state.Button.A == ButtonState.Pressed)
       ; // Button A was just released
    else
       ; // Button A is not pressed
 
    // Update state for the next frame
    old_state = state;
}